<template>
  <div class="work-space">
    <h1 class="title">Maintenance Tools</h1>
    <!-- <span v-if="VerticalRow">（{{ proName }}）</span> -->
    <!-- 库位 -->
    <div class="ku_wei">
      <div
        class="ku_fixed"
        :style="{ width: kwInfo.length > 1 ? '45vw' : '' }"
        v-for="(KW, KWINDEX) in kwInfo"
        :key="KW.LocationId"
      >
        <caption :class="[VerticalRow ? 'vCap' : '', 'cap']">
          <a-tooltip placement="top">
            <template slot="title" v-if="KW.MappingPointName">
              {{ KW.MappingPointName }}
            </template>
            {{ KW.MappingPointName }}
          </a-tooltip>
        </caption>
        <div
          v-if="!KW.CIDCode && !KW.CellRow && !KW.CellColumn"
          class="init_area"
        ></div>
        <div
          v-else
          :class="[VerticalRow ? 'vCenter' : '', Put_Rule_Class]"
          style="position: relative"
        >
          <div v-for="i in KW.CellRow" :key="i" class="block-boundary">
            <!-- 块内容 -->
            <div
              v-for="t in KW.CellColumn"
              :key="t"
              :style="{
                width: tdWidth(KW.CellColumn, KW.CellRow),
                height: tdHeight(KW.CellColumn, KW.CellRow),
              }"
              :class="[
                VerticalRow ? 'vCenter' : '',
                BlockHighlight() == BlockCellInfo(KW, i, t)?.n
                  ? 'block-boundary-cell-hight'
                  : 'block-boundary-cell',
                Put_Rule_block_Class(BlockCellInfo(KW, i, t)),
              ]"
            >
              <!-- <div>{{ (i - 1) * KW.CellColumn + t }}</div> -->
              <!-- <span
                style="
                  color: red;
                  font-size: 12px;
                  position: absolute;
                  z-index: 99;
                "
              >
                {{ "LRow" + BlockCellInfo(KW, i, t).LRow }}---{{
                  "LColumn" + BlockCellInfo(KW, i, t).LColumn
                }}
                {{ BlockCellInfo(KW, i, t)?.BlockTypeId
                }}{{ BlockCellInfo(KW, i, t)?.PutRule }}
              </span> -->
              <!-- 如果没有块就不显示 -->
              <table v-if="BlockCellInfo(KW, i, t)?.CellCount">
                <tr
                  v-for="cell_i in BlockCellInfo(KW, i, t)?.CellRow"
                  :key="cell_i"
                >
                  <td
                    v-for="cell_t in BlockCellInfo(KW, i, t)?.CellColumn"
                    :key="cell_t"
                    :style="{
                      width: blockCellWidth(
                        tdWidth(KW.CellColumn, KW.CellRow),
                        BlockCellInfo(KW, i, t)?.CellColumn
                      ),
                      height: blockCellHeight(
                        tdHeight(KW.CellColumn, KW.CellRow),
                        BlockCellInfo(KW, i, t)?.CellRow
                      ),
                    }"
                    :class="{
                      info: true,
                      bg_blue: reId(
                        i,
                        t,
                        KW,
                        'isWork',
                        cell_i,
                        cell_t,
                        BlockCellInfo(KW, i, t)
                      ),
                      bg_cyan:
                        !reId(
                          i,
                          t,
                          KW,
                          'KeyFlag',
                          cell_i,
                          cell_t,
                          BlockCellInfo(KW, i, t)
                        ) &&
                        reId(
                          i,
                          t,
                          KW,
                          'noKeyFlagFinish',
                          cell_i,
                          cell_t,
                          BlockCellInfo(KW, i, t)
                        ),
                      bg_red:
                        reId(
                          i,
                          t,
                          KW,
                          'KeyFlag',
                          cell_i,
                          cell_t,
                          BlockCellInfo(KW, i, t)
                        ) &&
                        reId(
                          i,
                          t,
                          KW,
                          'KeyFlagUnfinish',
                          cell_i,
                          cell_t,
                          BlockCellInfo(KW, i, t)
                        ),
                      bg_yellow:
                        reId(
                          i,
                          t,
                          KW,
                          'KeyFlag',
                          cell_i,
                          cell_t,
                          BlockCellInfo(KW, i, t)
                        ) &&
                        reId(
                          i,
                          t,
                          KW,
                          'KeyFlagForkFinish',
                          cell_i,
                          cell_t,
                          BlockCellInfo(KW, i, t)
                        ),
                      bg_green:
                        reId(
                          i,
                          t,
                          KW,
                          'KeyFlag',
                          cell_i,
                          cell_t,
                          BlockCellInfo(KW, i, t)
                        ) &&
                        reId(
                          i,
                          t,
                          KW,
                          'KeyFlagFinish',
                          cell_i,
                          cell_t,
                          BlockCellInfo(KW, i, t)
                        ),
                      bg_pink:
                        reId(
                          i,
                          t,
                          KW,
                          'IsSkip',
                          cell_i,
                          cell_t,
                          BlockCellInfo(KW, i, t)
                        ) == 'skip',
                      bg_complete: reId(
                        i,
                        t,
                        KW,
                        'complete',
                        cell_i,
                        cell_t,
                        BlockCellInfo(KW, i, t)
                      ),
                    }"
                    @click="handldClickTd(i, t, KWINDEX)"
                  >
                    <div
                      :style="{
                        fontSize: '14px',
                      }"
                      :class="[
                        Put_Rule_txt_Class(BlockCellInfo(KW, i, t)),
                        'pull_txt',
                      ]"
                    >
                      <span
                        v-if="
                          orderWarehouseList[KWINDEX][i - 1][t - 1]?.IsSkip !=
                          'skip'
                        "
                      >
                        {{
                          reId(
                            i,
                            t,
                            KW,
                            "ProductOrder",
                            cell_i,
                            cell_t,
                            BlockCellInfo(KW, i, t)
                          )
                        }}
                        {{
                          reId(
                            i,
                            t,
                            KW,
                            "FlowNo",
                            cell_i,
                            cell_t,
                            BlockCellInfo(KW, i, t)
                          )
                        }}
                        <!-- [{{
                          (cell_i - 1) * BlockCellInfo(KW, i, t).CellColumn +
                          cell_t -
                          1
                        }}] -->
                      </span>
                    </div>
                  </td>
                </tr>
              </table>
            </div>
          </div>
        </div>
        <div class="kw-title">
          库位 {{ KW.LocationId }}
          <span class="kw-code">({{ KW.CIDCode }})</span>
        </div>
        <div
          :style="{ right: kwInfo.length > 1 ? '0' : '-5vw' }"
          class="btn-group-fix"
        >
          <a-row>
            <a-col style="margin-bottom: 4px">
              <a-button
                class="item-btn"
                type="danger"
                @click="thumbnail(KWINDEX)"
                >托盘队列</a-button
              ></a-col
            >
            <a-col style="margin-bottom: 4px">
              <a-button
                class="item-btn"
                type="primary"
                @click="handleBind(KWINDEX)"
                >绑定</a-button
              ></a-col
            >
            <a-col>
              <a-button
                class="item-btn"
                type="primary"
                :disabled="completeCID.indexOf(KW.CIDCode) != -1"
                @click="Debounce_kwCompletet(KWINDEX)"
                >完成</a-button
              ></a-col
            >
          </a-row>
        </div>
      </div>
    </div>
    <!-- 器具 -->
    <div class="qi_ju">
      <div class="qi_ju_area">
        <a-checkbox-group
          @change="onChange"
          v-model="QJ_Select"
          style="width: 100%"
        >
          <div style="display: flex; justify-content: space-around">
            <div
              style="width: 33%"
              v-for="(descData, descIndex) in listData"
              :key="descData.id"
            >
              <a-checkbox :value="descData.value">
                <a-card
                  :style="{
                    background:
                      QJ_Select.indexOf(descIndex) !== -1
                        ? 'rgba(64, 158, 255, 0.4)'
                        : null,
                    position: 'relative',
                  }"
                  :title="descData.LocationId"
                  :class="{ qj_active: descData.qj_active, qj_ul: true }"
                  :bordered="true"
                >
                  <span slot="extra">{{ descData.CIDCode }}</span>

                  <!-- <ReturnEmpty
                    :boxEmptyImg="boxEmptyImg"
                    v-show="
                      (!descData.TaskInfo || descData.TaskInfo.length < 1) &&
                      selectLocation.indexOf(descData.LocationId) != -1
                    "
                    :descData="descData"
                    :QJ_Select="QJ_Select"
                    :descIndex="descIndex"
                  ></ReturnEmpty> -->
                  <a-list
                    item-layout="horizontal"
                    :data-source="descData.TaskInfo"
                    class="list-self"
                  >
                    <a-list-item
                      slot="renderItem"
                      slot-scope="item"
                      :style="{
                        background: item.isShow ? '#40a9ff' : '',
                        display: 'flex',
                        justifyContent: 'space-around',
                      }"
                    >
                      <div class="qj-list-item">
                        <div class="name">物料</div>
                        <div>{{ item.SkuName }}</div>
                      </div>
                      <div class="qj-list-item">
                        <div class="name">件号</div>
                        <div>{{ item.SkuId }}</div>
                      </div>
                      <div class="qj-list-item">
                        <div class="name">数量</div>
                        <div>{{ item.Qty }}</div>
                      </div>

                      <div class="qj-list-item">
                        <div class="name">拉动条码</div>
                        <a-tooltip placement="top">
                          <template slot="title">
                            <span>{{ item.BarCodeNumber }}</span>
                          </template>
                          <div class="pull_txt">{{ item.BarCodeNumber }}</div>
                        </a-tooltip>
                      </div>
                      <div class="qj-list-item">
                        <div class="name">供应商</div>
                        <div>{{ item.SupplierCode }}</div>
                      </div>
                    </a-list-item>
                  </a-list>
                </a-card>
                <div v-if="descData.qj_active" class="material-inventory">
                  <div>{{ MaterialInventory.SkuName }}</div>
                  <div style="margin: 0 20px">
                    {{ MaterialInventory.SkuId }}
                  </div>
                  <div>{{ MaterialInventory.Qty }}</div>
                </div>
              </a-checkbox>
            </div>
          </div>
        </a-checkbox-group>
      </div>
    </div>
    <!-- 按钮组 -->
    <div class="btn-group">
      <a-button size="large" class="sizeF" @click="showDrawer">
        任务列表
      </a-button>
      <a-button
        size="large"
        class="sizeF"
        type="dashed"
        @click="Debounce_abClick"
      >
        AB换面
      </a-button>
      <a-button
        size="large"
        class="sizeT"
        type="primary"
        @click="Debounce_Start"
      >
        开始
      </a-button>
      <!-- <a-button
        size="large"
        class="sizeT"
        type="danger"
        @click="Debounce_ClearAll"
        >退空</a-button
      > -->
      <!-- <a-button
        size="large"
        class="sizeT"
        type="primary"
        :disabled="feedingStatus"
        @click="Debounce_Feeding()"
      >
        投料
      </a-button> -->
      <a-button size="large" class="sizeF" @click="showDrawerS"
        >操作列表</a-button
      >
      <a-button
        size="large"
        class="size3"
        type="primary"
        @click="Debounce_NextStepJK"
        >下一步</a-button
      >
      <a-button size="large" key="back3" @click="Debounce_SkipLattic(1)"
        >跳过格口</a-button
      >
      <a-button size="large" class="sizeF" @click="showCode">补打条码</a-button>
      <TableSwitch
        :paramsInfo="{
          PointCode: this.workBenchCode[1],
          UserId: this.userName,
        }"
      />
    </div>
    <!-- 抽屉 -->
    <a-drawer
      title="任务列表"
      :placement="placement"
      closable
      :visible="visible"
      @close="onClose"
      width="100%"
    >
      <a-form-model
        :layout="taskForm.layout"
        :model="taskForm"
        style="margin-bottom: 15px"
      >
        <a-form-model-item label="发动机顺序号">
          <a-input
            placeholder="请输入"
            v-model="taskForm.ProductOrder"
            allowClear
          />
        </a-form-model-item>
        <a-form-model-item label="发动机序列号">
          <a-input
            placeholder="请输入"
            v-model="taskForm.ProductCode"
            allowClear
          />
        </a-form-model-item>
        <a-form-model-item label="生产计划日期">
          <a-date-picker
            v-model="taskForm.PlanDate"
            show-time
            type="date"
            :showTime="{ defaultValue: showTime }"
            :locale="locale"
            placeholder="请选择生产计划日期"
            style="width: 100%"
          />
        </a-form-model-item>
        <a-form-model-item label="生产计划状态">
          <a-select
            v-model="taskForm.Status"
            style="width: 200px"
            placeholder="请选择生产计划状态"
            allowClear
          >
            <a-select-option value="待处理">待处理</a-select-option>
            <a-select-option value="跳过"> 跳过 </a-select-option>
            <a-select-option value="已处理"> 已处理 </a-select-option>
            <a-select-option value="完成"> 完成 </a-select-option>
            <a-select-option value="强制完成"> 强制完成 </a-select-option>
            <a-select-option value="投料完成"> 投料完成 </a-select-option>
            <a-select-option value="托盘已运往产线投料点">
              托盘已运往产线投料点
            </a-select-option>
            <a-select-option value="排序完成投料未完成">
              排序完成投料未完成
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="primary" @click="taskSearch"> 查询 </a-button>
        </a-form-model-item>
      </a-form-model>
      <a-table
        :columns="columns"
        :pagination="paginationC"
        @change="handleTableChangeC"
        :rowKey="(r, i) => i"
        :data-source="dataC"
        bordered
        :scroll="{ y: taskScroll }"
      >
        <a slot="KeyFlag" slot-scope="KeyFlag">{{ KeyFlag }}</a>
      </a-table>
    </a-drawer>
    <!-- 抽屉 -->
    <a-drawer
      title="操作记录"
      :placement="placementS"
      closable
      :visible="visibleS"
      @close="onClose"
      width="100%"
    >
      <a-form-model
        :layout="operationForm.layout"
        :model="operationForm"
        style="margin-bottom: 15px"
      >
        <a-form-model-item label="生产计划日期">
          <a-date-picker
            v-model="operationForm.PlanDate"
            show-time
            type="date"
            :showTime="{ defaultValue: showTime }"
            :locale="locale"
            placeholder="请选择生产计划日期"
            style="width: 100%"
          />
        </a-form-model-item>
        <a-form-model-item label="扫描状态">
          <a-select
            v-model="operationForm.Status"
            style="width: 200px"
            placeholder="请选择生产计划状态"
            allowClear
          >
            <a-select-option value="创建">创建</a-select-option>
            <a-select-option value="漏扫"> 漏扫 </a-select-option>
            <a-select-option value="完成"> 完成 </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="primary" @click="operationSearch"> 查询 </a-button>
        </a-form-model-item>
      </a-form-model>
      <a-table
        :columns="columnsS"
        :data-source="dataS"
        :pagination="paginationS"
        @change="handleTableChangeS"
        :rowKey="(r, i) => i"
        bordered
        :scroll="{ width: 2800, y: taskScroll }"
      >
        <a slot="KeyFlag" slot-scope="KeyFlag">{{ KeyFlag }}</a>
      </a-table>
    </a-drawer>
    <div class="menu">
      <div class="work-bench">
        <!-- <div style="position: relative">
          <div class="mask"></div>
          <a-input-search
            :value="workBench"
            size="large"
            style="width: 200px"
            enter-button="选择"
            @search="showModal"
          />
        </div> -->
        <div class="avatar" @click="logout">
          <svg
            t="1665210772296"
            class="icon"
            viewBox="0 0 1024 1024"
            version="1.1"
            xmlns="http://www.w3.org/2000/svg"
            p-id="7019"
            width="200"
            height="200"
          >
            <path
              d="M512 566.613333c138.808889 0 251.448889-112.64 251.448889-251.448889 0-138.808889-112.64-251.448889-251.448889-251.448888s-251.448889 112.64-251.448889 251.448888c0 138.808889 112.64 251.448889 251.448889 251.448889z m0-446.008889c106.951111 0 194.56 87.608889 194.56 194.56S618.951111 509.724444 512 509.724444s-194.56-87.608889-194.56-194.56S405.048889 120.604444 512 120.604444zM869.262222 698.595556c-86.471111-52.337778-207.075556-78.506667-357.262222-78.506667s-270.791111 26.168889-357.262222 78.506667C104.675556 728.177778 73.955556 782.791111 73.955556 839.68v94.435556c0 15.928889 12.515556 28.444444 28.444444 28.444444h819.2c15.928889 0 28.444444-12.515556 28.444444-28.444444v-94.435556c0-56.888889-30.72-111.502222-80.782222-141.084444z m23.893334 207.075555h-762.311112v-65.991111c0-37.546667 20.48-72.817778 52.337778-93.297778 77.368889-46.648889 188.871111-70.542222 328.817778-70.542222 139.946667 0 250.311111 23.893333 328.817778 70.542222 32.995556 19.342222 52.337778 54.613333 52.337778 93.297778v65.991111z"
              p-id="7020"
              fill="#8a8a8a"
            ></path>
          </svg>
          <!-- <a-avatar
            src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
          /> -->
          <span class="login-name">{{ userName }}</span>
        </div>
      </div>
    </div>
    <!-- 选择产业/工位 -->
    <a-modal
      v-model="modalVisible"
      width="50%"
      title="选择产线 | 投料点"
      @ok="handleOk"
      ok-text="确认"
      cancel-text="取消"
    >
      <sel-work-bench
        @getWorKBenchValue="getWorKBenchValue"
        @getWorKBenchCode="getWorKBenchCode"
      ></sel-work-bench>
    </a-modal>
    <!-- 关键件扫描 -->
    <a-modal
      v-model="keyVisible"
      centered
      closable
      v-drag
      width="30vw"
      :maskClosable="false"
      :title="
        editorStatus
          ? `修改关键件(${editorItem && editorItem.ProductCode}-${
              editorItem && editorItem.ProductOrder
            })`
          : `关键件扫描(${findSelf && findSelf.ProductCode}-${
              findSelf && findSelf.ProductOrder
            })`
      "
    >
      <template #footer>
        <a-button key="back2" @click="Debounce_SkipLattic(1)"
          >跳过格口</a-button
        >
        <a-button
          key="forceSubmit"
          type="primary"
          @click="Debounce_KeyOk({ IsForceComplete: 1 })"
          @keyup.enter="onKeyUp(e)"
          >强制确认</a-button
        >
        <a-button key="back" @click="Debounce_KeyCancel">跳过</a-button>
        <a-button
          key="submit"
          type="primary"
          @click="Debounce_KeyOk({ IsForceComplete: 0 })"
          @keyup.enter="onKeyUp(e)"
          >确认</a-button
        >
      </template>
      <ScanComponent
        @getReturnReason="getReturnReason"
        @getForcedConfirmReason="getForcedConfirmReason"
        @getScanCode="getScanCode"
        @concludeData="concludeData"
        :keyVisible="keyVisible"
      />
      <!-- <a-row>
        <a-col span="16">
          <a-input
            size="large"
            v-model="scanCode"
            allow-clear
            ref="inputValue"
            placeholder="扫描件码"
            @keyup.native="concludeData"
        /></a-col>
        <a-col span="8" style="padding: 0 10px">
          <a-button size="large" type="primary" @click="onScanUpcKeyUp"
            >重新扫描</a-button
          >
        </a-col>
      </a-row>
      <a-row style="margin-top: 15px">
        <a-col span="24">
          <a-input
            size="large"
            placeholder="跳过原因"
            v-model="returnReason"
            allow-clear
            @blur="onScanUpcKeyUp2"
            @change="
              () => {
                this.forcedConfirmReason = '';
              }"
          ></a-input
        ></a-col>
        <a-input  placeholder="sbsbs" v-model="sbsb"></a-input>
      </a-row>
      <a-row style="margin-top: 15px">
        <a-col span="24">
          <a-input
            size="large"
            v-model.lazy="forcedConfirmReason"
            allow-clear
            placeholder="强制确认原因"
            @change="
              () => {
                this.returnReason = '';
              }
            "
          ></a-input
        ></a-col>
      </a-row> -->
    </a-modal>
    <!-- 绑定 -->
    <a-modal v-model="trayVisible" title="绑定">
      <template #footer>
        <a-button key="back" @click="trayVisible = false">取消</a-button>
        <a-button key="submit" type="primary" @click="bindOk">确认</a-button>
      </template>
      <a-form-model
        :model="form"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="托盘编号">
          <a-input v-model="form.tp_num" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item label="库位编码">
          <a-input v-model="form.kw_num" placeholder="请输入" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- msg弹框 -->
    <div v-show="msgCardShow" class="msg_card">
      <message-card
        ref="msgRef"
        :msgCardInfo="msgCardInfo"
        @msgIsShow="msgIsShow"
      ></message-card>
    </div>
    <!-- 图例 -->
    <div class="legend_card">
      <Legend></Legend>
    </div>
    <Html2Canvas
      :ThumbnailList="ThumbnailList"
      @dialogClose="dialogClose"
      :isShowHtml2Canvas="isShowHtml2Canvas"
      :Put_Rule="Put_Rule"
      :VerticalRow="VerticalRow"
      :kwInfo="detailKwInfo"
    />
    <BarCodeReprint
      :workBenchCode="workBenchCode"
      :drawer="drawer"
      @codeEmit="codeEmit"
    />
    <TaskQueue
      :dialogTableVisible="dialogTableVisible"
      @queueVisible="queueVisible"
      :QueueLocationId="QueueLocationId"
      @handleQueue="handleQueue"
    />
  </div>
</template>

<script>
import SelWorkBench from "@/components/SelWorkBench.vue";
import TaskQueue from "@/components/TaskQueue.vue";
import MessageCard from "@/components/MessageCard.vue";
import Legend from "@/components/Legend.vue";
import ReturnEmpty from "@/components/ReturnEmpty.vue";
import Html2Canvas from "@/components/Html2Canvas.vue";
import BarCodeReprint from "@/components/BarCodeReprint.vue";
import ScanComponent from "./ScanComponent.vue";
import { columns, columnsS } from "./tableColumns";
import { api } from "@/utils/api";
import { comparedArr, removeListItem } from "@/utils/tools";
import axios from "axios";
import _ from "lodash";
import locale from "ant-design-vue/es/date-picker/locale/zh_CN";
import moment from "moment";
import { InitLoc } from "@/utils/sortLoc";
import TableSwitch from "@/components/TableSwitch.vue";
import { mockSort } from "./mockSortData";
export default {
  name: "WorkBench",
  components: {
    SelWorkBench,
    MessageCard,
    Legend,
    ReturnEmpty,
    TableSwitch,
    Html2Canvas,
    BarCodeReprint,
    ScanComponent,
    TaskQueue,
  },
  props: {
    msg: String,
  },
  computed: {
    userName: () => {
      return sessionStorage.getItem("userName");
    },
    proName() {
      let str = "";
      if (this.kwInfo.length > 0 && this.kwInfo[1]) {
        str = this.kwInfo[1].MappingPointName;
      }
      if (this.kwInfo.length > 0 && this.kwInfo[0]) {
        str = this.kwInfo[0].MappingPointName;
      }
      return str;
    },
    showTime: () => {
      return moment("00:00:00", "HH:mm:ss");
    },
    selQJ() {
      return sessionStorage.getItem("selectLocationIdList")
        ? JSON.parse(sessionStorage.getItem("selectLocationIdList"))
        : [];
    },
    Put_Rule_Class() {
      return {
        top_right: this.Put_Rule == "top_right",
        top_left: this.Put_Rule == "top_left",
        bottom_left: this.Put_Rule == "bottom_left",
        bottom_right: this.Put_Rule == "bottom_right",
        // top_right_v: this.Put_Rule == "top_right_v",
        // top_left_v: this.Put_Rule == "top_left_v",
        // bottom_left_v: this.Put_Rule == "bottom_left_v",
        // bottom_right_v: this.Put_Rule == "bottom_right_v",
      };
    },
    Put_Rule_block_Class() {
      return function (block) {
        // console.log("Put_Rule_block_Class", block, block.PutRule);
        if (this.Put_Rule == "top_left" && block?.PutRule == "top_left_v") {
          return "B_top_left_block_top_left_v";
        }
        if (this.Put_Rule == "top_right") {
          return "b_top_right";
        }
        if (this.Put_Rule == "bottom_left") {
          return "top_left_block_v";
        }
        if (this.Put_Rule == "bottom_right") {
          return "bottom_right_block";
        }
        // if (this.Put_Rule == "bottom_left_v") {
        //   return "bottom_left_txt_v";
        // }
        // if (this.Put_Rule == "top_right_v") {
        //   return "top_right_txt_v";
        // }
        // if (this.Put_Rule == "bottom_right_v") {
        //   return "bottom_right_txt_v";
        // }
        // if (this.Put_Rule == "bottom_left") {
        //   return "bottom_left_txt";
        // }
      };
    },
    Put_Rule_txt_Class() {
      return function (block) {
        // console.log("Put_Rule_txt_Class", block, block.PutRule);
        if (this.Put_Rule == "top_right") {
          return "b_top_right_txt";
        }
        //   if (this.Put_Rule == "top_left_v") {
        //   return "top_left_txt_v";
        // }
        // if (this.Put_Rule == "bottom_left_v") {
        //   return "bottom_left_txt_v";
        // }
        // if (this.Put_Rule == "top_right_v") {
        //   return "top_right_txt_v";
        // }
        // if (this.Put_Rule == "bottom_right_v") {
        //   return "bottom_right_txt_v";
        // }
        // if (this.Put_Rule == "bottom_left") {
        //   return "bottom_left_txt";
        // }
        // if (this.Put_Rule == "top_right") {
        //   return "top_right";
        // }
        // if (this.Put_Rule == "bottom_right") {
        //   return "bottom_right";
        // }
      };
    },
    BlockCellInfo() {
      return function (KW, i, t) {
        let item = KW.BlockDetails[(i - 1) * KW.CellColumn + t - 1];
        // if(item.CellCount) {
          // return item
        // } else {
        //   return {}
        // }
        console.log('KW, i, t', KW, i, t,KW.BlockDetails[(i - 1) * KW.CellColumn + t - 1],KW.BlockDetails[(i - 1) * KW.CellColumn + t - 1].CellCount);
        return KW.BlockDetails[(i - 1) * KW.CellColumn + t - 1];
      };
    },
    captionWidth() {
      return function (CellColumn, CellRow) {
        let w = 10;
        if (CellRow == 1) {
          w = 100 / CellColumn;
        } else {
          w = 480 / (CellColumn < CellRow ? CellColumn : CellRow) / 12;
        }
        return w * CellColumn + "vh";
      };
    },
    tdWidth() {
      return function (CellColumn, CellRow) {
        let w = 80 / CellColumn + "vw";
        if (this.kwInfo.length == 1 && CellColumn > 9) {
          w = 80 / CellColumn + "vw";
        }
        if (this.VerticalRow) {
          w = 80 / CellColumn + "vw";
        }
        // console.log(
        //   "CellColumn, CellRow tdWidth",
        //   CellColumn,
        //   CellRow,
        //   w,
        //   this.VerticalRow
        // );
        return w;
      };
    },
    blockCellWidth() {
      return function (cellWidth, CellColumn) {
        const W = cellWidth.match(/\d+/)[0] / CellColumn + "vw";
        return W;
      };
    },
    blockCellHeight() {
      return function (cellHeight, CellRow) {
        const H = (cellHeight.match(/\d+/)[0] - 1) / CellRow + "vh";
        return H;
      };
      //  console.log(
      //   "blockCellWidth------>>>>",
      //   cellWidth,
      //   CellColumn,
      //   //   CellRow,
      //   W
      //   //   this.VerticalRow
      // );
    },
    tdHeight() {
      return function (CellColumn, CellRow) {
        let h = 40 / CellRow + "vh";
        // if (CellColumn == 1) {
        //   h = 40 / CellRow + "vh";
        // } else {
        //   h = 40 / CellRow + "vh";
        // }
        // if (this.VerticalRow) {
        //   h = 40 / CellRow + "vw";
        // }
        // console.log(
        //   "CellColumn, CellRow tdHeight",
        //   CellColumn,
        //   CellRow,
        //   h,
        //   this.VerticalRow
        // );
        return h;
      };
    },
    kwHeight() {
      return function (CellColumn, CellRow) {
        let h = 10;
        if (CellColumn == 1) {
          h = 50 / CellRow;
        } else {
          h = 480 / (CellColumn < CellRow ? CellColumn : CellRow) / 12;
        }
        return h * CellRow + "vh";
      };
    },
  },
  data: () => {
    return {
      //控制换块提示
      rearEnd: true,
      dialogTableVisible: false,
      QueueLocationId: "",
      rearEndkeyVisible: true,
      drawer: false,
      boxEmptyImg: require("@/assets/image/box-empty.png"),
      StartingState: true, //控制上面两个托盘规格从无到有只触发一次接口
      MaterialInventory: {},
      keyContinuousStatus: true,
      COMPELETEBTN: true,
      isContinue: true,
      MatchingTag: false,
      isShowHtml2Canvas: false,
      InitLoc: [],
      Put_Rule: "",
      // 竖向排横向排
      VerticalRow: false,
      timearr: [],
      selectLocation: [],
      dataC: [],
      paginationC: {},
      paginationS: {},
      columns,
      dataS: [],
      columnsS,
      // 完成的库位
      completeCID: [],
      // 托盘完成状态
      completeState: [false, false],
      // 器具信息
      listData: [
        { PointName: "物料一" },
        { PointName: "物料二" },
        { PointName: "物料三" },
      ],
      // 通知card
      msgCardShow: false,
      workBenchCode: [],
      // 库位下标
      kwIndex: 0,
      // 库位信息
      kwInfo: [{ name: "库位一" }, { name: "库位二" }],
      // 库位信息
      orderWarehouseList: [],
      // orderWarehouseList具体项
      orderWarehouseItem: {},
      // 区别？
      listOutItem: {},
      // listData具体项
      listItem: {},
      // 下一步当前下标
      stepIndex: 0,
      KWTP_LEFT: "",
      KWTP_RIGHT: "",
      // 来源cidname
      originCIDName: "",
      // 器具选择
      QJ_Select: [],
      // 卡片信息
      msgCardInfo: {},
      // 编辑状态
      editorStatus: false,
      // 投料按钮
      feedingStatus:
        sessionStorage.getItem("feedingStatus") == "true" ? true : false,
      // 修改项信息
      editorItem: {},
      // 当前skuid
      curSkuId: "",
      // 跳过or确定
      setType: "",
      // 并列键
      isBLJ: false,
      timerGroup: {
        timer1: null,
        timer2: null,
      },
      timer: null,
      planBearkTimer: null,
      Warning_timer: null,
      // 点击哪一个库位
      clickKwIndex: 0,
      // 点击横坐标
      clickP: 0,
      // 点击纵坐标
      clickC: 0,
      // 未分格子的数组
      kwAccordList: [],
      kwAccordCopyList: [],
      ThumbnailList: [],
      // 从那一项开始
      findSelf: {},
      detailKwInfo: {},
      // 托盘轮询
      kwInfoTP: [],
      workBench: "",
      keyVisible: false,
      trayVisible: false,
      scanCode: "",
      // 跳过原因
      returnReason: "",
      // 强制确认原因
      forcedConfirmReason: "",
      started: false,
      modalVisible: false,
      visible: false,
      placement: "left",
      visibleS: false,
      placementS: "right",
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      form: {
        tp_num: "",
        kw_num: "",
      },
      taskForm: {
        layout: "inline",
        PlanDate: "",
        Status: "",
      },
      operationForm: {
        layout: "inline",
        PlanDate: "",
        Status: "",
      },
      taskScroll: 300,
      locale,
    };
  },
  watch: {
    KWTP_LEFT(newVal, oldVal) {
      // console.log(
      //   " KWTP_LEFT oldVal, newVal------>>>",
      //   newVal,
      //   oldVal,
      //   typeof oldVal,
      //   this.started,
      //   newVal != "",
      //   oldVal === null
      // );
      if (this.started && newVal != "" && oldVal === null) {
        let trayList = this.clearTray(0);
        // console.log(
        //   "watch kwInfo----->>> 0000 关闭定时器 trayList",
        //   newVal,
        //   oldVal,
        //   trayList
        // );
        this.$set(this.orderWarehouseList, 0, trayList);
        clearInterval(this.timerGroup.timer1);
        this.timerGroup.timer1 = null;
        this.init();
      }
    },
    KWTP_RIGHT(newVal, oldVal) {
      // console.log(" KWTP_RIGHT oldVal, newVal------>>>", newVal, oldVal);
      if (this.started && newVal != "" && oldVal === null) {
        let trayList = this.clearTray(1);
        this.$set(this.orderWarehouseList, 1, trayList);
        console.log("watch kwInfo----->>> 0000 关闭定时器", newVal, oldVal);
        clearInterval(this.timerGroup.timer2);
        this.timerGroup.timer2 = null;
        this.init();
      }
    },
    kwInfo(newVal, oldVal) {
      if (newVal && newVal?.length > 0) {
        newVal.forEach((e, eIndex) => {
          if (e?.LocationId && !e?.CIDCode) {
            this.tp(e.LocationId, 10000, eIndex);
            this.StartingState = true;
          } else {
            if (
              eIndex == 0 &&
              this.timerGroup.timer1 &&
              this.completeCID.length < 1
            ) {
              clearInterval(this.timerGroup.timer1);
              this.timerGroup.timer1 = null;
              this.getCidsInfo(this.workBenchCode);
              this.init();
            }
            if (
              eIndex == 1 &&
              this.timerGroup.timer2 &&
              this.completeCID.length < 1
            ) {
              clearInterval(this.timerGroup.timer2);
              this.timerGroup.timer2 = null;
              this.getCidsInfo(this.workBenchCode);
              this.init();
            }
            // if (this.StartingState) {
            //   this.getCidsInfo(this.workBenchCode);
            //   this.init();
            //   this.StartingState = false;
            // }
          }
        });
      }
    },
    completeCID: {
      handler(newVal) {
        if (newVal.length > 0) {
          newVal.forEach((f) => {
            const qjIndex = this.kwInfo.findIndex((k) => k.CIDName === f);
            const kwCid = this.kwInfo.map((k) => k.CIDCode);
            if (qjIndex != -1) {
              const { LocationId } = this.kwInfo[qjIndex];
              this.tp(LocationId, 10000, qjIndex);
            } else {
              this.$message({
                type: "warning",
                message:
                  "排序库位 " +
                  JSON.stringify(newVal) +
                  " 和 " +
                  JSON.stringify(kwCid) +
                  " 库位托盘对应不上",
              });
              return;
            }
          });
        }
      },
      deep: true,
    },
    // scanCode: {
    // handler(newVal) {
    //   if (newVal) {
    //     // this.$refs.inputValue?.select();
    //     let res = false;
    //     let Qty = 1;
    //     if (/^&+/.test(newVal)) {
    //       res = true;
    //       this.isBLJ = true;
    //       if (res) {
    //         Qty = newVal.split("&").pop() * 1; //大于0
    //       } else {
    //         Qty = this.findSelf.Qty * 1;
    //       }
    //       let keyIndex = this.kwAccordList.findIndex(
    //         (kw) =>
    //           kw.ProductOrder === this.findSelf.ProductOrder &&
    //           kw.ProductCode === this.findSelf.ProductCode &&
    //           kw.PackSort === this.findSelf.PackSort &&
    //           kw.PlanDate === this.findSelf.PlanDate &&
    //           kw.BarCodeNumber === this.findSelf.BarCodeNumber &&
    //           kw.SkuId === this.findSelf.SkuId &&
    //           !kw.isCom
    //       );
    //       let tagIndex = this.kwAccordList[keyIndex].tagIndex;
    //       console.log(
    //         "********扫描关键件scanCode watcher*********",
    //         Qty,
    //         keyIndex,
    //         tagIndex
    //       );
    //       if (!isNaN(Qty) && Qty > 0 && Qty < 1000) {
    //         this.kwAccordList = _.cloneDeep(this.kwAccordCopyList);
    //         for (let j = 0; j < Qty; j++) {
    //           this.$set(
    //             this.kwAccordList[keyIndex + j],
    //             "tagIndex",
    //             tagIndex
    //           );
    //         }
    //         this.randomLun();
    //         this.redrawGrid();
    //       }
    //     }
    //     // if (res) {
    //     //   Qty = newVal.split("&").pop() * 1; //大于0
    //     // } else {
    //     //   Qty = this.findSelf.Qty * 1;
    //     // }
    //     // let keyIndex = this.kwAccordList.findIndex(
    //     //   (kw) =>
    //     //     kw.ProductOrder === this.findSelf.ProductOrder &&
    //     //     kw.ProductCode === this.findSelf.ProductCode &&
    //     //     kw.PackSort === this.findSelf.PackSort &&
    //     //     kw.PlanDate === this.findSelf.PlanDate &&
    //     //     kw.BarCodeNumber === this.findSelf.BarCodeNumber &&
    //     //     kw.SkuId === this.findSelf.SkuId &&
    //     //     !kw.isCom
    //     // );
    //     // let tagIndex = this.kwAccordList[keyIndex].tagIndex;
    //     // console.log("********扫描关键件scanCode watcher*********", Qty, keyIndex, tagIndex);
    //     // if (!isNaN(Qty) && Qty > 0 && Qty < 1000) {
    //     //   this.kwAccordList = _.cloneDeep(this.kwAccordCopyList);
    //     //   for (let j = 0; j < Qty; j++) {
    //     //     this.$set(this.kwAccordList[keyIndex + j], "tagIndex", tagIndex);
    //     //   }
    //     //   this.randomLun();
    //     //   this.redrawGrid();
    //     // }
    //   }
    // },
    // },
  },
  created() {
    clearInterval(this.timer);
    clearInterval(this.planBearkTimer);
    clearInterval(this.timerGroup.timer1);
    clearInterval(this.timerGroup.timer2);
    clearInterval(this.Warning_timer);
    this.Warning_timer = null;
    this.timer = null;
    this.planBearkTimer = null;
    this.timerGroup.timer1 = null;
    this.timerGroup.timer2 = null;
  },
  async mounted() {
    let workBench = localStorage.getItem("workBenchName");
    let LcWorkBench = localStorage.getItem("workBench");
    const PL = JSON.parse(localStorage.getItem("ProductList"));
    // if (!this.userName) {
    //   this.$router.replace("login");
    // }
    if (workBench && LcWorkBench) {
      this.workBench = workBench;
      this.selectLocation = this.selQJ;
      if (LcWorkBench) {
        this.workBenchCode = JSON.parse(LcWorkBench);
        // 换块预警
        this.blockchangeWarning();
      }
      this.InitLoc = InitLoc(PL, this.workBenchCode);
      this.getQJ().then((res) => {
        this.getCidsInfo(this.workBenchCode);
      });

      // 换块预警轮询
      this.setIntervalWarning(15000);
      //   this.lx(10000);
      //   this.planBearkLX(4 * 60 * 60 * 1000); //4h
    } else {
      this.$message({
        type: "warning",
        message: "请先选择产线|投料点",
      });
      this.$router.push("/login");
      return;
    }
    this.taskScroll = window.innerHeight - 290;
  },
  destroyed: function () {
    // 每次离开当前界面时，清除定时器
    clearInterval(this.timer);
    clearInterval(this.planBearkTimer);
    clearInterval(this.timerGroup.timer1);
    clearInterval(this.timerGroup.timer2);
    clearInterval(this.Warning_timer);
    this.Warning_timer = null;
    this.timer = null;
    this.planBearkTimer = null;
    this.timerGroup.timer1 = null;
    this.timerGroup.timer2 = null;
    window.removeEventListener("keydown", this.onKeyUp, false);
  },
  methods: {
    BlockHighlight() {
      let n = 0;
      let N = sessionStorage.getItem("BlockHighlight_N");
      if (N) {
        n = N;
      } else {
        n = this.kwInfo[0].BlockDetails.findIndex((item) => !item?.BlockTypeId);
      }
      // console.log("BlockHighlight_N", N, n);
      // sessionStorage.removeItem("BlockHighlight_N");
      return n;
    },
    setIntervalWarning(delay) {
      let that = this;
      if (this.Warning_timer == null) {
        this.Warning_timer = setInterval(() => {
          that.blockchangeWarning();
        }, delay);
      }
    },
    blockchangeWarning() {
      const [ProductLineCode, PointCode] = this.workBenchCode;
      api.getBlockchangeWarning({ ProductLineCode, PointCode }).then((res) => {
        // console.log('blockchangeWarning', res);
        if (res[1].code == 0 && res[1].message) {
          this.$message({
            message: res[1].message,
            type: "warning",
            duration: 14000,
          });
        }
      });
    },
    createAndSortMatrix(array, direction) {
      const sqrtLength = Math.sqrt(array.length);
      console.log(
        "sqrtLength",
        sqrtLength,
        Math.floor(sqrtLength),
        sqrtLength !== Math.floor(sqrtLength)
      );
      // if (sqrtLength !== Math.floor(sqrtLength)) {
      //     throw new Error('Array length must be a perfect square to form a matrix.');
      // }
      const matrixSize = Math.floor(sqrtLength);
      const matrix = new Array(matrixSize);
      for (let i = 0; i < matrixSize; i++) {
        matrix[i] = new Array(matrixSize).fill(0);
      }

      let row = 0;
      let col = 0;
      let incrementRow = 1;
      let incrementCol = 1;

      switch (direction) {
        case "左上":
          // 默认从左到右，从上到下
          break;
        case "左下":
          row = matrixSize - 1; // 从底部开始
          incrementRow = -1; // 向上移动
          break;
        case "右上":
          col = matrixSize - 1; // 从右侧开始
          incrementCol = -1; // 向左移动
          break;
        case "右下":
          row = matrixSize - 1; // 从底部开始
          col = matrixSize - 1; // 从右侧开始
          incrementRow = -1; // 向上移动
          incrementCol = -1; // 向左移动
          break;
        default:
          throw new Error("Invalid direction");
      }

      for (let num of array) {
        matrix[row][col] = num; // 填充当前位置

        //     // 更新行列索引
        // row += incrementRow;
        // col += incrementCol;

        //     // 如果到达边界，则反转增量方向
        //     if (row < 0 || row >= matrixSize || col < 0 || col >= matrixSize) {
        //         [row, col] = [matrixSize - 1 - row, matrixSize - 1 - col]; // 移动到对称位置
        //         [incrementRow, incrementCol] = [-incrementRow, -incrementCol]; // 反转增量方向
        //     }
      }
      console.log("sqrtLength", matrix);
      return matrix;
    },
    changeConfirm(content, data) {
      if (data.ischangeblock == 1) {
        // 后端提示换块前端换块逻辑关闭
        this.rearEnd = false;
        this.rearEndkeyVisible = false;
        this.showChangeBlockConfirm(content, data);
        this.rearEndBlockHighlight(data.nextLRow, data.nextLColumn);
      }
      if (data.ischangectype == 1) {
        this.showChangeTypeConfirm(content, data);
      }
    },
    showChangeBlockConfirm(content, data) {
      this.$confirm(content, "换块", {
        confirmButtonText: "确定",
        // cancelButtonText: "取消",
        type: "warning",
        closeOnClickModal: false,
      })
        .then(() => {
          // 写死0
          // let unique = this.findSelf.unique;
          // let CellColumn = this.kwInfo[0].CellColumn;
          // let num =
          //   unique < CellColumn
          //     ? CellColumn - unique
          //     : CellColumn - (unique % CellColumn);
          // this.skipLatticePlus(num);
          console.log("showChangeBlockConfirm", 0, data);
          sessionStorage.removeItem("BlockHighlight_N");
          this.updatejdwBlockCids(data.isPresent, data, "rear-end");
        })
        .catch(() => {
          sessionStorage.removeItem("BlockHighlight_N");
          this.$message({
            type: "info",
            message: "已取消换块",
          });
        });
    },
    showChangeTypeConfirm(content, data) {
      this.$confirm(content, "换类型", {
        confirmButtonText: "确定",
        // cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 写死0
          this.kwComplete(0);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    getReturnReason(val) {
      this.returnReason = val;
    },
    getForcedConfirmReason(val) {
      this.forcedConfirmReason = val;
    },
    getScanCode(val) {
      this.scanCode = val;
    },
    dialogClose(val) {
      this.isShowHtml2Canvas = val;
    },
    taskSearch() {
      let PlanDate = "";
      if (this.taskForm.PlanDate) {
        PlanDate = moment(this.taskForm.PlanDate).format("YYYY-MM-DD HH:mm:ss");
      }
      this.getProduceplans({
        pageIndex: 0,
        pageSize: 10,
        Status: this.taskForm.Status,
        ProductOrder: this.taskForm.ProductOrder,
        ProductCode: this.taskForm.ProductCode,
        PlanDate,
      });
    },
    operationSearch() {
      let PlanDate = "";
      if (this.operationForm.PlanDate) {
        PlanDate = moment(this.operationForm.PlanDate).format(
          "YYYY-MM-DD HH:mm:ss"
        );
      }
      this.getScanInfoList({
        pageIndex: 0,
        pageSize: 10,
        Status: this.operationForm.Status,
        PlanDate,
      });
    },
    // 扫描自动确认
    concludeData(e) {
      if (e.code === "Enter") {
        console.log("扫描自动确认", this.scanCode);
        this.keyOk({ IsForceComplete: 0 }, "扫描自动确认 concludeData");
      }
    },
    // 重新扫描
    onScanUpcKeyUp() {
      this.scanCode = "";
      this.$nextTick(() => {
        this.$refs.inputValue.focus(); //聚焦
      });
    },
    onScanUpcKeyUp2() {
      this.$nextTick(() => {
        this.$refs.inputValue.focus(); //聚焦
      });
    },
    // 物料滚动
    rolling(leftIndex, rightIndex) {
      let htmlDom = document.getElementsByClassName("qj_ul");
      let CardDom = document.getElementsByClassName("list-self");
      let cardHeight = CardDom[leftIndex].offsetHeight;
      // 当前器具总共的物料数量
      let total = this.listData[leftIndex]?.TaskInfo?.length;
      // 每一个list的高度
      let listHeight = ((cardHeight * 1) / total) * 1;
      // console.log("物料滚动", listHeight, total, leftIndex, rightIndex);
      // 当前高亮的位置
      let currentHighlight = rightIndex + 1;
      if (currentHighlight > 2) {
        htmlDom[leftIndex].lastChild.scrollTop =
          listHeight * (currentHighlight - 3);
        // htmlDom[leftIndex].lastChild.scrollTop = listHeight * (total - 2);
      }
    },
    // 分解任务
    planPullBreakup() {
      let LcWorkBench = localStorage.getItem("workBench");
      if (LcWorkBench) {
        LcWorkBench = JSON.parse(LcWorkBench);
      }
      const [ProductLineCode, PointCode] = LcWorkBench;
      const params = {
        data: {
          UserId: this.userName,
          ProductLineCode,
          PointCode,
        },
      };
      axios.post("/gui/wcsz/v1/plan/pull/breakup", params).then((res) => {
        // console.log("planPullBreakup----->>>", res);
      });
      // api.planPullBreakupAPI(params).then((res) => {
      // console.log("planPullBreakup----->>>", res);
      // });
    },
    // 缓存的产线|工位是否在接口中，不在就重新选择
    async hasStationsPoints(workBenchCode) {
      let pTag = false;
      let sTag = false;
      let wTag = false;
      let PL = JSON.parse(workBenchCode);
      let czList = this.listData.map((m) => m.LocationId);
      let nList = [];
      let [ERR, GRES] = await api.getStationsPointsAPI();
      if (GRES.code === 0) {
        GRES.data.forEach((m) => {
          if (m.ProductLineCode == PL[0]) {
            pTag = true;
          }
          if (m.PointCodes.length > 0) {
            m.PointCodes.forEach((M) => {
              if (M.PointCode == PL[1]) {
                sTag = true;
              }
              nList = M.PointLocationIds?.map((ids) => ids.LocationId);
            });
          }
        });
        wTag = comparedArr(czList, nList);
      }
      console.log("true", czList, nList, wTag);
      if (pTag && sTag && !wTag) {
        localStorage.removeItem("workBench");
        localStorage.removeItem("workBenchName");
      }
    },
    // 缓存的产线|工位 有就直接显示
    showProductionLine() {
      const workBenchCode = localStorage.getItem("workBench");
      if (workBenchCode) {
        this.hasStationsPoints(workBenchCode);
      }
    },
    // 是否禁用托盘完成按钮
    getCompleteState() {
      this.orderWarehouseList.forEach((item, index) => {
        let res = item.flat(2);
        if (res.every((e) => e.complete)) {
          this.completeState[index] = true;
        }
      });
    },
    // 获取产线|投料点
    getWorKBenchValue(data) {
      this.workBench = data;
    },
    // 获取产线|投料点code
    getWorKBenchCode(data) {
      this.workBenchCode = data;
    },
    // 获取器具物料
    getQJ() {
      return new Promise((resolve, reject) => {
        const PL = JSON.parse(localStorage.getItem("ProductList"));
        const [ProductLineCode, PointCode] = this.workBenchCode;
        if (PL && Array.isArray(PL)) {
          const list = PL.filter((f) => f.ProductLineCode === ProductLineCode);
          // console.log("xxxxxx", list);
          if (list.length > 0) {
            let FL = list[0].PointCodes?.filter(
              (f) => f.PointCode === PointCode
            );
            let pointsList = FL[0]?.PointLocationIds;
            let PointName = FL[0]?.PointName;
            // const Put_Rule = "top_left";
            // const Put_Rule = 'bottom_left';
            // const Put_Rule = 'top_right';
            // const Put_Rule = 'bottom_right';

            // const Put_Rule = "top_left_v";
            // const Put_Rule = "top_right_v";
            // const Put_Rule = "bottom_left_v";
            // const Put_Rule = "bottom_right_v";

            const Put_Rule = FL[0]?.Put_Rule;
            localStorage.setItem("Put_Rule", Put_Rule);
            this.Put_Rule = Put_Rule;
            this.VerticalRow = Put_Rule?.indexOf("v") != -1;
            const test = [];
            pointsList?.forEach((pItem) => {
              const params = {
                ProductLineCode,
                PointCode,
                LocationId: pItem.LocationId,
              };
              test.push(api.getPointtasksAPI(params));
            });
            // console.log("获取器具物料", FL, pointsList, test);
            if (test.length > 0) {
              Promise.all(test)
                .then((res) => {
                  let resList = [];
                  res.forEach((rItem, rIndex) => {
                    if (rItem.length > 0)
                      if (rItem[1].data?.IsEmpty == 1) {
                        this.$message({
                          type: "warning",
                          message: `托盘【${rItem[1].data.CIDCode}】原料已消耗完`,
                        });
                      }
                    resList.push({
                      PointCode,
                      PointName,
                      ...rItem[1].data,
                      TaskInfo: rItem[1].data.TaskInfo?.map((m) => ({
                        ...m,
                      })),
                      LocationId: pointsList[rIndex].LocationId,
                      value: rIndex,
                    });
                  });
                  this.listData = resList;
                  // console.log("getQJ", resList);
                  resolve(resList);
                })
                .catch((err) => {
                  reject(err);
                });
            }
          }
        }
      });
    },
    // 半天轮询一次分解
    planBearkLX(delay) {
      if (this.planBearkTimer == null) {
        this.planBearkTimer = setInterval(() => {
          // this.planPullBreakup();
        }, delay);
      }
    },
    // 轮询物料任务
    lx(delay) {
      if (this.timer == null) {
        this.timer = setInterval(() => {
          const [ProductLineCode, PointCode] = this.workBenchCode;
          let pointsList = [];
          const test = [];
          // TaskInfo[]没有信息就需要轮询
          this.listData.forEach((item) => {
            if (!item.TaskInfo || item.TaskInfo.length < 1) {
              if (item.PointCode) pointsList.push(item.LocationId);
            }
          });
          pointsList?.forEach((LocationId) => {
            const params = {
              ProductLineCode,
              PointCode,
              LocationId,
            };
            test.push(api.getPointtasksAPI(params));
          });
          if (test.length > 0) {
            Promise.all(test).then((res) => {
              // console.log("轮询物料任务", res);
              res.forEach((rItem) => {
                if (Array.isArray(rItem[1].data.TaskInfo)) {
                  let { LocationId } = rItem[1].data;
                  let rIndex = this.listData.findIndex(
                    (f) => f.LocationId == LocationId
                  );
                  this.$set(this.listData, rIndex, {
                    ...this.listData[rIndex],
                    // txt: "冲冲冲" + fIndex,
                    ...rItem[1].data,
                    TaskInfo: rItem[1].data.TaskInfo?.map((m) => ({
                      ...m,
                    })),
                  });
                }
              });
            });
          }
        }, delay);
      }
    },
    // 清空某个库位托盘
    clearTray(i) {
      let list = this.orderWarehouseList[i];
      let resList = list.map((l) => {
        return l.map((ll) => {
          return {
            ...ll,
            ProductOrder: "",
            isWork: false,
            isCom: false,
            KeyFlagFinish: false,
            KeyFlagUnfinish: false,
            KeyFlagForkFinish: false,
            noKeyFlagFinish: false,
            complete: false,
          };
        });
      });
      return resList;
    },
    // 轮询库位托盘
    tp(LocationId, delay, i) {
      // console.log("************轮询库位托盘*************", LocationId, i);
      let index = ++i;
      clearInterval(this.timerGroup["timer" + index]);
      this.timerGroup["timer" + index] = null;
      this.timerGroup["timer" + index] = setInterval(async () => {
        const [ProductLineCode, PointCode] = this.workBenchCode;
        const params = {
          ProductLineCode,
          PointCode,
        };
        let [ERR, GRES] = await api.getJDWCidsInfoAPI(params);
        if (GRES.code === 0) {
          let gRes = GRES.data;
          let res = gRes;
          if (gRes[0].LocationId != this.InitLoc[0]) {
            res = gRes.reverse();
          }
          let findIndex = res.findIndex(
            (item) => item.LocationId === LocationId
          );
          let mapList = res.find((item) => item.LocationId === LocationId);
          this.$set(this.kwInfoTP, findIndex, mapList?.CIDCode);
          if (findIndex == 0) this.KWTP_LEFT = mapList?.CIDCode;
          if (findIndex == 1) this.KWTP_RIGHT = mapList?.CIDCode;
          this.$set(this.kwInfo, findIndex, {
            ...mapList,
          });

          // console.log(
          //   "$$$$$$$$$$$$$轮询库位托盘$$$$$$$$$$",
          //   findIndex,
          //   mapList,
          //   i
          // );
        }
      }, delay);
    },
    // 库位初始化（画格子）
    getCidsInfo(workBenchCode) {
      return new Promise(async (resolve, reject) => {
        console.log(" 库位初始化（画格子）");
        const [ProductLineCode, PointCode] = workBenchCode;
        const params = {
          ProductLineCode,
          PointCode,
        };
        let [ERR, GRES] = await api.getJDWCidsInfoAPI(params);
        let hasBlockDetails = true;
        if (GRES.code === 0) {
          if (GRES.data.length > 0) {
            let gRes = GRES.data.map((M) => {
              let BlockDetails = [];
              if (M.BlockDetails && M.BlockDetails.length > 0) {
                BlockDetails = M.BlockDetails.map((m, n) => ({ ...m, n }));
              } else {
                this.$message({
                  type: "warning",
                  message: `请配置托盘块信息`,
                });
                hasBlockDetails = false;
              }
              if (hasBlockDetails) {
                return { ...M, BlockDetails };
              } else {
                return { ...M };
              }
            });
            resolve("success");

            // const Put_Rule = "top_left";
            // const Put_Rule = 'bottom_left';
            // const Put_Rule = 'top_right';
            // const Put_Rule = 'bottom_right';

            // const Put_Rule = 'top_left_v';
            // const Put_Rule = 'top_right_v';
            // const Put_Rule = "bottom_left_v";
            // const Put_Rule = 'bottom_right_v';
            // this.PutRule = Put_Rule;
            console.log("this.Put_Rule", this.Put_Rule, gRes);
            // if (
            //   this.Put_Rule == "top_left_v" ||
            //   this.Put_Rule == "top_right_v" ||
            //   this.Put_Rule == "bottom_left_v" ||
            //   this.Put_Rule == "bottom_right_v"
            // ) {
            //   gRes = gRes.map((M) => {
            //     let BlockDetails = [];
            //     if (M.BlockDetails.length > 0) {
            //       BlockDetails = M.BlockDetails.map((m) => ({
            //         ...m,
            //         CellColumn: m.CellRow,
            //         CellRow: m.CellColumn,
            //       }));
            //     }
            //     return {
            //       ...M,
            //       BlockDetails,
            //       CellColumn: M.CellRow,
            //       CellRow: M.CellColumn,
            //     };
            //   });
            //   console.log("GRES.data", gRes);
            // }
            let res = gRes;

            if (gRes[0].LocationId != this.InitLoc[0]) {
              res = gRes.reverse();
            }
            this.kwInfo = res.map((m) => ({ ...m, c: 0, p: 0, m: "m" }));
            res.forEach((r, rIndex) => {
              this.$set(this.kwInfoTP, rIndex, r.CIDCode);
            });
            res.forEach((rItem, rIndex) => {
              let outList = [];
              for (let j = 0; j < rItem.CellRow; j++) {
                let arr = new Array(rItem.CellColumn).fill({
                  id: "",
                  isWork: false,
                  isCom: false,
                });
                outList[j] = arr;
              }
              this.orderWarehouseList[rIndex] = outList;
            });
          } else {
            const PL = JSON.parse(localStorage.getItem("ProductList"));
            const [ProductLineCode, PointCode] = this.workBenchCode;
            if (PL && Array.isArray(PL)) {
              const list = PL.filter(
                (f) => f.ProductLineCode === ProductLineCode
              );
              if (list.length > 0) {
                let FL = list[0].PointCodes?.filter(
                  (f) => f.PointCode === PointCode
                );
                let LocationIds = FL[0]?.LocationIds;
                this.kwInfo = LocationIds;
              }
            }
          }
        }
      });
    },
    // 后端给的要亮的位置
    rearEndBlockHighlight(LRow, LColumn) {
      let rearEndBlock = this.kwInfo[0].BlockDetails.find(
        (f) => f.LRow == LRow && f.LColumn == LColumn
      );
      sessionStorage.setItem("BlockHighlight_N", rearEndBlock.n);
      return rearEndBlock.n;
    },
    // （更新格子）
    async updatejdwBlockCids(isPresent = 1, data = {}, tag) {
      console.log("（更新格子）", isPresent, data);
      const [ProductLineCode, PointCode] = this.workBenchCode;
      const { CIDCode } = this.kwInfo[0];
      let LRow = "";
      let LColumn = "";
      if (tag == "rear-end") {
        LRow = data.Row_Column.split("-")[0] * 1;
        LColumn = data.Row_Column.split("-")[1] * 1;
      }
      if (tag == "client") {
        LRow = this.CurrentBlockLoc().LRow;
        LColumn = this.CurrentBlockLoc().LColumn;
      }
      let params = {
        data: {
          ProductLineCode,
          PointCode,
          ToCID: CIDCode,
          UserId: this.userName,
          LRow,
          LColumn,
          PutRule: this.Put_Rule,
          isPresent,
        },
      };

      let [ERR, GRES] = await api.updatejdwBlockCidsAPI(params);
      if (GRES.code === 0) {
        this.getCidsInfo(this.workBenchCode).then(() => {
          this.init();
        });
      }
    },
    onKeyUp(e) {
      if (e.keyCode === 13) {
        this.keyOk({ IsForceComplete: 0 }, "onKeyUp");
        console.log("onKeyUponKeyUponKeyUp");
      }
    },
    // 绑定
    handleBind(index) {
      this.trayVisible = true;
      this.kwIndex = index;
      this.form.kw_num = this.kwInfo[index].LocationId;
      this.form.tp_num = "";
    },
    // 查询工位操作记录
    async getScanInfoList(data) {
      const [ProductLineCode, PointCode] = this.workBenchCode;
      if (data.current) delete data.current;
      if (data.total) delete data.total;
      const params = { ProductLineCode, PointCode, ...data };
      let [ERR, GRES] = await api.getScanInfoAPI(params);
      if (GRES.code === 0) {
        const pagination = { ...this.paginationS };
        pagination.total = GRES.totalcount;
        this.dataS = GRES.data;
        this.paginationS = pagination;
      }
    },
    handleTableChangeC(pagination) {
      console.log(pagination);
      this.paginationC = pagination;
      this.getProduceplans({ pageIndex: pagination.current - 1, pageSize: 10 });
    },
    handleTableChangeS(pagination) {
      console.log(pagination);
      this.paginationS = pagination;
      this.getScanInfoList({ pageIndex: pagination.current - 1, pageSize: 10 });
    },
    // 查询生产计划任务
    async getProduceplans(data) {
      const [ProductLineCode, PointCode] = this.workBenchCode;
      if (data.current) delete data.current;
      if (data.total) delete data.total;
      const params = { ProductLineCode, PointCode, ...data };
      let [ERR, GRES] = await api.getProduceplansAPI(params);
      if (GRES.code === 0) {
        const pagination = { ...this.paginationC };
        pagination.total = GRES.totalcount;
        this.dataC = GRES.data;
        this.paginationC = pagination;
      }
    },
    // 退出登录
    logout() {
      this.$confirm("退出登录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$router.push("login");
        sessionStorage.clear();
        this.$message({
          type: "success",
          message: "退出成功!",
        });
      });
    },
    // 渲染td内容
    reId(row, col, KW, ProductOrder, cell_i, cell_t, gz_kw) {
      let res = "";
      // 外层大托盘下标排序
      let DGZOrder = (row - 1) * KW.CellColumn + col;
      // 内层块格子下标排序
      let XGZOrder = (cell_i - 1) * gz_kw.CellColumn + cell_t;
      let item = this.orderWarehouseList[DGZOrder - 1];
      if (item) {
        item = item[XGZOrder - 1];
        // console.log("渲染td内容", DGZOrder + "-----" + XGZOrder, item);
        res = item && item[ProductOrder];
      }
      if (item && item.IsSkip && item.IsSkip == "skip") {
        res = "";
      }
      return res;
    },
    // 摆盘缩略图
    thumbnail(i) {
      this.dialogTableVisible = true;
      console.log("摆盘缩略图", i);
      this.QueueLocationId = this.kwInfo[i]?.LocationId;
    },
    queueVisible(val) {
      this.dialogTableVisible = val;
    },
    handleQueue(val) {
      if (val.code == 0) {
        this.getCidsInfo(this.workBenchCode).then(() => {
          this.init();
        });
      }
    },
    // thumbnail(i) {
    //   let ThumbnailList = this.orderWarehouseList[i];
    //   this.detailKwInfo = this.kwInfo[i];
    //   this.ThumbnailList = ThumbnailList;
    //   this.isShowHtml2Canvas = true;
    //   console.log("摆盘缩略图", ThumbnailList);
    // },
    // 库位清空
    async kwReset(i) {
      if (!this.canStart()) {
        this.$message({
          type: "warning",
          message: "请先绑定托盘",
        });
        return;
      }
      const [ProductLineCode, PointCode] = this.workBenchCode;
      let list = this.orderWarehouseList[i];
      const params = {
        app_name: "gui",
        data: {
          CID: this.kwInfo[i].CIDCode,
          ProductLineCode,
          PointCode,
          UserId: this.userName,
        },
      };
      let [ERR, DRES] = await api.delCidScan(params);
      console.log("@@@@@@@@", DRES);
      let res = list.map((l) => {
        return l.map((ll) => ({
          ...ll,
          isWork: false,
          isCom: false,
          KeyFlagFinish: false,
          noKeyFlagFinish: false,
          KeyFlagUnfinish: false,
          KeyFlagForkFinish: false,
        }));
      });
      this.$set(this.orderWarehouseList, i, res);
    },
    // 库位完成接口
    async kwCidFull(i) {
      const [ProductLineCode, PointCode] = this.workBenchCode;
      const params = {
        app_name: "gui",
        data: {
          CID: this.kwInfo[i].CIDCode,
          ProductLineCode,
          PointCode,
          UserId: this.userName,
        },
      };
      let [ERR, ARES] = await api.cidFull(params);
      return ARES;
    },
    // 启停输送带
    async Transit_PLC(index, data) {
      let LocationId = this.kwInfo[index]?.LocationId;
      let taskid = data?.deliveryId;
      let params = {
        data: [{ LocationId, taskid }],
      };
      let [ERR, ARES] = await api.Transit_PLC_API(params);
      // JSON.stringify(obj) === '{}'
      // success_list
      console.log(
        "启停输送带 JSON.stringify(ARES?.error_list)",
        JSON.stringify(ARES?.error_list),
        JSON.stringify(ARES?.error_list) === "{}"
      );
      if (JSON.stringify(ARES?.error_list) === "{}") {
        this.$message({
          type: "success",
          message: "请求传送带滚动成功",
        });
      } else {
        this.$message({
          type: "warning",
          message: "请求传送带滚动失败",
        });
      }
    },
    Debounce_kwCompletet: _.debounce(function (i) {
      // 这里不能用箭头，不然获取不到 this 实例
      this.kwComplete(i);
    }, 500),
    // 库位完成
    kwComplete(i) {
      if (!this.kwInfo[i].CIDCode) {
        this.$message({
          type: "warning",
          message: "请先绑定托盘",
        });
        return;
      }
      this.kwCidFull(i).then((res) => {
        if (res.code === 0) {
          this.$message({
            type: "success",
            message: "成功",
          });
          this.getCidsInfo(this.workBenchCode);
          this.Transit_PLC(i, res);
          this.init();
          let LocationId = this.kwInfo[i].LocationId;
          this.tp(LocationId, 100000, i);
        }
      });
    },
    // 是否可以开始
    canStart() {
      // 至少有一个托盘才能开始
      let boolean = this.kwInfo.some((item) => item.CIDCode);
      // let tag = true;
      // 两个托盘都有任务就禁止开始
      // if (this.orderWarehouseList.length > 0) {
      //   tag = this.orderWarehouseList.some((sItem) => {
      //     return sItem.some((s) => s.isWork);
      //   });
      // }
      // console.log("是否可以开始", boolean, tag, this.orderWarehouseList, this.orderWarehouseList.length);
      // return boolean && !tag;
      return boolean;
    },
    // 是否有物料投放任务
    hasTaskInfo() {
      let boolean = this.listData.some((item) => item.TaskInfo);
      return boolean;
    },
    // 获取记录下标
    getHistoryIndex(list) {
      let that = this;
      let only = list.find((l) => l.Status === "待处理");
      // console.log("获取记录下标", only); // TaskId
      if (only) {
        this.orderWarehouseList.forEach((a, ai) => {
          if (a.length > 0) {
            a.forEach((b, bi) => {
              b.forEach((c, ci) => {
                if (c.TaskId === only.TaskId) {
                  // console.log("ccccc", ai, bi, ci);
                  that.stepIndex = ai;
                  that.kwInfo[ai].p = bi;
                  that.kwInfo[ai].c = ci;
                }
              });
            });
          }
        });
      }
    },
    // 从哪个库位开始排序
    capLocationStart() {
      let res = [0, 1];
      let start_cid = this.kwAccordList[0].CID;
      if (this.kwInfo.length > 1) {
        if (start_cid) {
          let startIndex = this.kwInfo.findIndex(
            (f) => f.CIDCode === start_cid
          );
          if (startIndex == 1) {
            res = [1, 0];
          }
          console.log("从哪个库位开始排序******", this.kwInfo, startIndex);
        }
      } else {
        res = [0];
      }
      return res;
    },
    // 未分格子的基础数组
    kwAccordDeal(list) {
      const sum = this.kwInfo.reduce((pre, cur) => {
        return pre + cur.CellCount;
      }, 0);
      this.kwAccordList = list.slice(0, sum);
    },
    // 处理基本数组
    kwMapList(list, str) {
      // console.log("处理基本数组---->>>", list, breakUpList);
      let resList = list.map((m, mIndex) => {
        return {
          ...m,
          tagIndex: mIndex,
          unique: mIndex,
          isWork: m.Status !== "待处理" ? true : false,
          isCom: m.Status !== "待处理" ? true : false,
          KeyFlag: m.KeyFlag === "是" ? true : false,
          complete:
            m.Status === "排序完成投料未完成" || m.Status === "完成"
              ? true
              : false,
          KeyFlagFinish:
            m.KeyFlag === "是" && m.Status === "已处理" ? true : false,
          noKeyFlagFinish:
            m.KeyFlag === "否" && m.Status === "已处理" ? true : false,
          KeyFlagUnfinish:
            m.KeyFlag === "是" && m.Status === "跳过" ? true : false,
          KeyFlagForkFinish:
            m.KeyFlag === "是" && m.Status === "强制完成" ? true : false,
        };
      });
      console.log("处理基本数组----->>>", list, resList, str);
      return resList;
    },
    // 处理排序完成的sort排列
    kwComStatusList(mapList) {
      // 排序的cid可能会和库位的cid对应不上，报错
      let isError = false;
      let completeCidList = [];
      // console.log("处理排序完成的sort排列---->>>", mapList);
      let fliterCompleteList = mapList.filter((f) => f.complete && f.CID);
      fliterCompleteList.forEach((f) => {
        completeCidList.push(f.CID);
      });
      // 排序完成的器具
      let completeCID = [...new Set(completeCidList)];
      this.completeCID = completeCID;
      completeCID.forEach((cid) => {
        //格子数量 托盘对应不上该值为undefind
        let check_the_number = this.kwInfo.find(
          (f) => f.CIDCode === cid
        )?.CellCount;
        // 实际数量
        let actual_number = mapList
          .filter((f) => f.complete && f.CID === cid)
          ?.reduce((pre, r) => {
            return pre + r.real_qty * 1;
          }, 0);
        // 打散完成的
        mapList.forEach((f, fIndex) => {
          if (f.real_qty > 1 && f.CID === cid) {
            let concatArr = Array(f.real_qty).fill({
              ...e,
            });
            mapList.splice(fIndex + 1, 1, ...concatArr);
          }
        });

        // 相差的数量
        let difference_number = check_the_number * 1 - actual_number * 1;
        let completeLastIndex = mapList.findLastIndex(
          (f) => f.complete && f.CID === cid
        );
        // console.log(
        //   "处理排序完成的sort排列---->>>",
        //   completeCID,
        //   check_the_number,
        //   actual_number,
        //   difference_number,
        //   completeLastIndex + 1
        // );
        // console.log("&*&%^%^%*^**22222", difference_number);
        if (difference_number >= 0) {
          let concatArr = Array(difference_number).fill({
            isWork: false,
            ProductOrder: "",
            CID: cid,
          });
          // console.log("&*&%^%^%*^**", concatArr);
          mapList.splice(completeLastIndex + 1, 0, ...concatArr);
        } else {
          isError = true;
        }
      });
      if (isError) {
        return [];
      } else {
        return mapList;
      }
    },
    // 是否有可操作的托盘
    anOperableTray() {
      let arr = this.kwInfo.map((m) => m.CIDCode).filter((f) => f);
      let isSetGo = comparedArr(arr, this.completeCID);
      // console.log("是否有可操作的托盘", arr, isSetGo);
      return isSetGo;
    },
    Debounce_Start: _.debounce(function () {
      // 这里不能用箭头，不然获取不到 this 实例
      this.start(true);
    }, 500),
    // 需要处理的数量（全部块的格子数量）
    getCount() {
      let nums = this.kwInfo[0].BlockDetails.reduce(
        (accumulator, currentValue) =>
          accumulator + (currentValue.CellCount ? currentValue.CellCount : 0),
        0
      );
      // console.log('getCount', nums);
      return nums;
    },
    NeedBlock(G_Data) {
      let res = [];
      let { CellColumn, CellRow } = this.kwInfo[0];
      let BlockDetails = this.kwInfo[0].BlockDetails;
      // console.log("NeedBlock_CellColumn == 1", G_Data, this.Put_Rule);
      // _v单列的时候带bottom需要计划列表反转，带top可不处理
      if (
        CellColumn == 1 &&
        (this.Put_Rule == "bottom_left_v" || this.Put_Rule == "bottom_right_v")
      ) {
        G_Data.reverse();
      }
      if (this.Put_Rule == "top_left_v" && CellColumn != 1) {
        let list = [];
        let factIndex = 0; //块列表其中可能会有空缺

        BlockDetails.forEach((blockItem, BlockIndex) => {
          let miniList = [];
          if (blockItem.CellCount) {
            miniList = G_Data.slice(
              factIndex * blockItem.CellCount,
              (factIndex + 1) * blockItem.CellCount
            );
            factIndex = factIndex + 1;

            list.push(miniList);
          }
        });
        // 列
        for (let i = 0; i < CellRow; i++) {
          let c = list.filter((_, index) => (index + i) % CellRow === 0); // 取第1行的元素
          res.push(c);
          console.log("NeedBlockccccc", c);
        }
      }
      if (this.Put_Rule == "top_right_v" && CellColumn != 1) {
        let list = [];
        let factIndex = 0; //块列表其中可能会有空缺
        BlockDetails.forEach((blockItem, BlockIndex) => {
          let miniList = [];
          console.log(
            "NeedBlock_top_right_v_list_blockItem.CellCount",
            blockItem.CellCount,
            BlockIndex * blockItem.CellCount,
            (BlockIndex + 1) * blockItem.CellCount
          );

          if (blockItem.CellCount) {
            miniList = G_Data.slice(
              factIndex * blockItem.CellCount,
              (factIndex + 1) * blockItem.CellCount
            );
            factIndex = factIndex + 1;
            list.push(miniList);
          }
        });
        console.log("NeedBlock_top_right_v_list", list);

        // 列
        for (let i = 0; i < CellRow; i++) {
          let c = list
            .filter((_, index) => (index + i) % CellRow === 0)
            .reverse(); // 取第1行的元素
          res.push(c);
          console.log("NeedBlock_top_right_v", c);
        }
        console.log("NeedBlock_top_right_v", res.flat(2), G_Data);
      }
      if (this.Put_Rule == "bottom_left_v" && CellColumn != 1) {
        let list = [];
        let factIndex = 0; //块列表其中可能会有空缺
        BlockDetails.forEach((blockItem, BlockIndex) => {
          let miniList = [];
          if (blockItem.CellCount) {
            miniList = G_Data.slice(
              factIndex * blockItem.CellCount,
              (factIndex + 1) * blockItem.CellCount
            );
            factIndex = factIndex + 1;
            list.push(miniList);
          }
        });
        // 列
        for (let i = 0; i < CellRow; i++) {
          let c = list.filter((_, index) => (index + i) % CellRow === 0); // 取第1行的元素
          res.push(c);
          console.log("NeedBlockccccc", c);
        }
        res = res.reverse();
        console.log("NeedBlock", res, res.flat(2), G_Data);
      }
      if (this.Put_Rule == "bottom_right_v" && CellColumn != 1) {
        let list = [];
        let factIndex = 0; //块列表其中可能会有空缺
        console.log("bottom_right_v", G_Data);
        BlockDetails.forEach((blockItem, BlockIndex) => {
          let miniList = [];
          if (blockItem.CellCount) {
            miniList = G_Data.slice(
              factIndex * blockItem.CellCount,
              (factIndex + 1) * blockItem.CellCount
            );
            factIndex = factIndex + 1;
            list.push(miniList);
          }
        });
        // 列
        for (let i = 0; i < CellRow; i++) {
          let c = list
            .filter((_, index) => (index + i) % CellRow === 0)
            .reverse(); // 取第1行的元素
          res.push(c);
          console.log("NeedBlockccccc", c);
        }
        res = res.reverse();
        console.log("NeedBlock", res, res.flat(2), G_Data);
      }
      if (res.length > 0) {
        return res.flat(2);
      } else {
        return G_Data;
      }
    },
    // 开始
    async start(isLoading = false) {
      console.log("******开始", this.getCount(), this.canStart());
      this.editorStatus = false;
      this.keyVisible = false;
      this.keyContinuousStatus = true;
      if (this.canStart()) {
        const [ProductLineCode, PointCode] = this.workBenchCode;
        let sortAPI = isLoading
          ? api.getLoadingProduceplansSortAPI
          : api.getProduceplansSortAPI;
        let [ERR, GRES] = await sortAPI({
          ProductLineCode,
          PointCode,
        });
        if (GRES.code === 0) {
          if (GRES.data && GRES.data.length > 0) {
            // const G_Data = mockSort.slice(0, this.getCount());
            let G_Data = GRES.data;
            // 补齐数据
            if (G_Data.length > this.getCount()) {
              G_Data = G_Data.slice(0, this.getCount());
            }
            if (G_Data.length < this.getCount()) {
              let num = this.getCount() * 1 - G_Data.length;
              let concatList = Array(num).fill({ Status: "待处理" });
              G_Data = G_Data.concat(...concatList);
            }
            console.log("G_Data", G_Data, G_Data.length, this.getCount());

            this.kwAccordCopyList = this.kwMapList(G_Data, "copy");
            if (this.Put_Rule.indexOf("v") > 0) {
              G_Data = this.NeedBlock(G_Data);
            }
            const mapList = this.kwMapList(G_Data, "no_copy");
            // const comStatusList = this.kwComStatusList(mapList);
            console.log(
              "??????????",
              this.Put_Rule.indexOf("v") != 0,
              this.findSelf,
              GRES.data,
              mapList
            );
            if (mapList.length > 0) {
              this.kwAccordList = mapList;
              // this.getHistoryIndex(G_Data);
              this.started = true;
              this.nextStep();
            }
          } else {
            this.$message({
              type: "warning",
              message: "请先激活生产计划",
            });
          }
        }
      } else {
        this.$message({
          type: "warning",
          message: "请先绑定托盘",
        });
        return;
      }
    },
    Debounce_abClick: _.debounce(function () {
      this.abClick();
    }, 500),
    // AB换面
    async abClick() {
      if (this.QJ_Select.length > 0) {
        const { CIDCode, LocationId } = this.listData[this.QJ_Select[0]];
        const params = {
          data: {
            CID: CIDCode,
            FromLoc: LocationId,
            UserId: this.userName,
            Type: "AB换面",
          },
        };
        let [ERR, ARES] = await api.ABchangeAPI(params);
        if (ARES.code === 0) {
          this.$message({
            type: "success",
            message: ARES.message,
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请先选择器具",
        });
      }
    },
    Debounce_ClearAll: _.debounce(function () {
      // 这里不能用箭头，不然获取不到 this 实例
      this.clearAll();
    }, 500),
    // 退空
    async clearAll() {
      let promiseList = [];
      let feedList = [];
      if (this.QJ_Select.length > 0) {
        this.QJ_Select.forEach((fItem) => {
          const { CIDCode, LocationId } = this.listData[fItem];
          feedList.push(LocationId);
          const params = {
            data: {
              CID: CIDCode,
              FromLoc: LocationId,
              UserId: this.userName,
              Type: "退空",
            },
          };
          promiseList.push(api.cidEmpty(params));
        });
        if (promiseList.length > 0) {
          Promise.all(promiseList).then((res) => {
            let flatList = res.flat(Infinity);
            let mapList = flatList.filter((m) => m);
            let isSuccessful = mapList.every((e) => e.code === 0);
            if (isSuccessful) {
              this.QJ_Select = [];
              this.$message({
                type: "success",
                message: "退空成功",
              });
              feedList.forEach((LocationId) => {
                this.feeding(LocationId);
                this.resetSelectLocationIdList(LocationId);
              });
            }
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请先选择器具",
        });
      }
    },
    Debounce_Feeding: _.debounce(function () {
      // 这里不能用箭头，不然获取不到 this 实例
      this.feeding();
    }, 500),
    // 投料激活
    async feeding(LocationId = "") {
      sessionStorage.setItem("feedingStatus", true);
      this.feedingStatus = true;
      const [ProductLineCode, PointCode] = this.workBenchCode;
      const params = {
        app_name: "gui",
        data: {
          ProductLineCode,
          PointCode,
          LocationId,
          UserId: this.userName,
        },
      };
      let [ERR, ARES] = await api.pointtasksActivationAPI(params);
      if (ARES.code === 0) {
        this.$message({
          type: "success",
          message: ARES.message,
        });
      }
    },
    // 接受消息弹窗状态
    msgIsShow(boolean) {
      this.msgCardShow = boolean;
    },
    showModal() {
      this.modalVisible = true;
    },
    // 任务列表
    showDrawer() {
      this.visible = true;
      this.msgCardShow = false;
      this.getProduceplans({
        ...this.paginationC,
        pageIndex: this.paginationC.current ? this.paginationC.current - 1 : 0,
      });
    },
    // 操作列表
    showDrawerS() {
      this.visibleS = true;
      this.msgCardShow = false;
      this.getScanInfoList({
        ...this.paginationS,
        pageIndex: this.paginationS.current ? this.paginationS.current - 1 : 0,
      });
    },
    showCode() {
      this.drawer = true;
    },
    codeEmit() {
      this.drawer = false;
    },
    // 工业|产线确定
    handleOk() {
      this.modalVisible = false;
      this.getCidsInfo(this.workBenchCode);
      this.getQJ();
    },
    // 抽屉关闭
    onClose() {
      this.visible = false;
      this.visibleS = false;
    },
    // 批量跳过格口数量
    getSkipNum(item) {
      if (item) {
        let start = this.kwAccordList.findIndex(
          (f) =>
            f.ProductOrder === this.findSelf.ProductOrder &&
            f.unique === this.findSelf.unique
        );
        let end = this.kwAccordList.findIndex(
          (f) =>
            f.ProductOrder === item.ProductOrder && f.unique === item.unique
        );
        // console.log("批量跳过格口数量", start, end);
        return end * 1 - start * 1;
      }
    },
    // 批量跳过格口
    BatchSkipGrid(num, item) {
      this.$confirm(
        "此操作将从【" +
          item.ProductOrder +
          "-" +
          +item.SkuId +
          "】位置跳过格口, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.skipLattice(num);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 点击关键件KeyFlagFinish td
    handldClickTd(p, c, KWINDEX) {
      this.editorStatus = true;
      this.msgCardShow = false;
      this.clickKwIndex = KWINDEX;
      this.clickP = p - 1;
      this.clickC = c - 1;
      let item = this.orderWarehouseList[KWINDEX][p - 1][c - 1];
      this.editorItem = item;
      let KeyFlag = item.KeyFlag;
      let KeyFlagFinish = item.KeyFlagFinish;
      let KeyFlagUnfinish = item.KeyFlagUnfinish;
      let KeyFlagForkFinish = item.KeyFlagForkFinish;
      let SkipReason = item.SkipReason;
      let ForceReason = item.ForceReason;
      let Type = item.Type;
      let isWork = item.isWork;
      let ProductOrder = item.ProductOrder;
      if (!isWork && ProductOrder) {
        this.BatchSkipGrid(this.getSkipNum(item), item);
      }
      if (Type == "并列件") {
        this.$message({
          type: "warning",
          message: "并列件不支持修改",
        });
        return;
      }
      // 关键件确定
      if (
        KeyFlag &&
        (KeyFlagFinish || KeyFlagForkFinish) &&
        this.rearEndkeyVisible
      ) {
        this.keyVisible = true;
        this.forcedConfirmReason = ForceReason;
        this.returnReason = SkipReason;
      }
      // 关键件跳过
      if (KeyFlag && KeyFlagUnfinish && this.rearEndkeyVisible) {
        this.keyVisible = true;
        this.scanCode = "";
        this.forcedConfirmReason = ForceReason;
        this.returnReason = SkipReason;
      }
      this.$nextTick(() => {
        this.$refs.inputValue?.focus(); //聚焦
      });
    },
    dealObject(fItem, qjList, i) {
      return {
        PointTaskBillId: qjList[i].PointTaskBillId,
        FromCID: qjList[i].CIDCode,
        Qty: 1,
        // Qty: qjList[i].Qty,
        ToCID: fItem.CIDCode,
        ProductOrder: fItem.ProductOrder,
        ProductCode: fItem.ProductCode,
        BarCodeNumber: fItem.BarCodeNumber,
        PackSort: fItem.PackSort,
        PlanDate: fItem.PlanDate,
        SkuId: fItem.SkuId,
        FlowNo: fItem.FlowNo,
        TaskId: qjList[i].TaskId,
        OrderLineNo: qjList[i].OrderLineNo,
        BoxCode: qjList[i].BoxCode,
        BatchNo: qjList[i].BatchNo,
      };
    },
    // 过滤参数
    filterParmes(item) {
      return {
        FlowNo: item.FlowNo,
        ProductOrder: item.ProductOrder,
        ProductCode: item.ProductCode,
        PlanDate: item.PlanDate,
        BarCodeNumber: item.BarCodeNumber,
        PackSort: item.PackSort,
        SkuId: item.SkuId,
        Qty: item.Qty,
        Layer: item.Layer,
      };
    },
    getDetailParmes() {
      let res = [];
      const { BarCodeNumber } = this.findSelf;
      let sList = this.orderWarehouseList
        .flat(Infinity)
        .filter((f) => f.isSelect);
      let xList = this.listItem[0]?.TaskInfo?.filter(
        (f) => f.BarCodeNumber == BarCodeNumber
      );
      const sSum = sList.length;
      const xSum = xList.reduce((pre, cur) => {
        return pre + cur.Qty;
      }, 0);
      let FromCID = this.listItem[0]?.CIDCode;
      let PointTaskBillId = this.listItem[0]?.PointTaskBillId;
      // 上面比下面物料少
      if (sSum <= xSum && xList.length <= 1) {
        sList.forEach((item) => {
          let BoxCode = xList[0].BoxCode;
          let BatchNo = xList[0].BatchNo;
          let TaskId = xList[0].TaskId;
          let OrderLineNo = xList[0].OrderLineNo;
          res.push({
            ...this.filterParmes(item),
            BoxCode,
            TaskId,
            OrderLineNo,
            BatchNo,
            ToCID: item.CIDCode,
            FromCID,
            PointTaskBillId,
          });
        });
      }
      // 上面比下面物料多
      if (sSum > xSum && xList.length <= 1) {
        let Qty = xList[0].Qty;
        let BoxCode = xList[0].BoxCode;
        let BatchNo = xList[0].BatchNo;
        let TaskId = xList[0].TaskId;
        let OrderLineNo = xList[0].OrderLineNo;
        let sliceList = sList.slice(0, Qty).map((m) => ({
          ...this.filterParmes(m),
          BoxCode,
          FromCID,
          BatchNo,
          TaskId,
          OrderLineNo,
          PointTaskBillId,
          ToCID: m.CIDCode,
        }));
        res = res.concat(sliceList);
      }
      // 上面比下面物料多
      if (sSum > xSum && xList.length > 1) {
        let Qty = xList.length;
        // 上面匹配数量多（物料不够时）强制截取上面的展示
        // this.QZ_Slice = xList.length;

        let BoxCode = xList[0].BoxCode;
        let BatchNo = xList[0].BatchNo;
        let TaskId = xList[0].TaskId;
        // let OrderLineNo = xList[0].OrderLineNo;
        let sliceList = sList.slice(0, Qty).map((m, i) => ({
          ...this.filterParmes(m),
          BoxCode,
          FromCID,
          BatchNo,
          TaskId,
          OrderLineNo: xList[i].OrderLineNo,
          PointTaskBillId,
          ToCID: m.CIDCode,
        }));
        res = res.concat(sliceList);
      }
      if (sSum <= xSum && xList.length > 1) {
        let start = 0;
        let end = 0;
        xList.forEach((xItem) => {
          const BoxCode = xItem.BoxCode;
          const BatchNo = xItem.BatchNo;
          const TaskId = xItem.TaskId;
          const OrderLineNo = xItem.OrderLineNo;
          let Qty = xItem.Qty;
          end = end + Qty;
          let sliceList = sList.slice(start, end).map((m) => ({
            ...this.filterParmes(m),
            BoxCode,
            FromCID,
            TaskId,
            BatchNo,
            OrderLineNo,
            PointTaskBillId,
            ToCID: m.CIDCode,
          }));
          res = res.concat(sliceList);
          start = end;
          console.log("xxxxxx", BoxCode, Qty, sliceList);
        });
      }
      console.log("getDetailParmes", sList, xList, sSum, xSum, res);
      return res;
    },
    // 参数detail处理
    dealDetail() {
      let detail = [];
      // 满足的库位
      let fliterFirst = this.fliterFirstFlatItem();
      let fliterFirstLength = fliterFirst.length;
      // 满足的器具
      let qjList = this.listItem;
      let qjListLength = 1;
      console.log("参数detail处理", qjListLength, fliterFirst);
      // let qjListLength = qjList.length;
      if (qjListLength === 1) {
        fliterFirst.forEach((fItem) => {
          detail.push(this.dealObject(fItem, qjList, 0));
        });
      }
      if (qjListLength === 2) {
        if (qjList[0].Qty > fliterFirstLength) {
          fliterFirst.forEach((fItem) => {
            detail.push(this.dealObject(fItem, qjList, 0));
          });
        } else {
          let sum = 0;
          fliterFirst.forEach((fItem) => {
            sum = sum + 1;
            if (sum > qjList[0].Qty) {
              detail.push(this.dealObject(fItem, qjList, 1));
            } else {
              detail.push(this.dealObject(fItem, qjList, 0));
            }
          });
        }
      }
      if (qjListLength === 3) {
        if (qjList[0].Qty > fliterFirstLength) {
          fliterFirst.forEach((fItem) => {
            detail.push(this.dealObject(fItem, qjList, 0));
          });
        } else if (qjList[0].Qty + qjList[1].Qty > fliterFirstLength) {
          let sum = 0;
          fliterFirst.forEach((fItem) => {
            sum = sum + 1;
            if (sum > qjList[0].Qty) {
              detail.push(this.dealObject(fItem, qjList, 1));
            } else {
              detail.push(this.dealObject(fItem, qjList, 0));
            }
          });
        } else if (
          qjList[0].Qty + qjList[1].Qty + qjList[2].Qty >
          fliterFirstLength
        ) {
          let sum = 0;
          fliterFirst.forEach((fItem) => {
            sum = sum + 1;
            if (qjList[0].Qty >= sum) {
              detail.push(this.dealObject(fItem, qjList, 0));
            } else if (qjList[0].Qty + qjList[1].Qty >= sum) {
              detail.push(this.dealObject(fItem, qjList, 1));
            } else if (qjList[0].Qty + qjList[1].Qty + +qjList[2].Qty >= sum) {
              detail.push(this.dealObject(fItem, qjList, 2));
            }
          });
        }
      }
      // console.log("&&&&&&&&&&&&&&&&&", fliterFirst, qjListLength, detail);
      return detail;
    },
    // 当前块
    CurrentBlock() {
      let CurrentBlock = this.orderWarehouseList
        .flat(Infinity)
        .find((f) => f.unique == this.findSelf.unique);
      return CurrentBlock;
      // let BlockDetails = [
      //   {
      //     BlockTypeId: "block5",
      //     BlockTypeName: "block5",
      //     LRow: 2,
      //     LColumn: 1,
      //     CellRow: 3,
      //     CellColumn: 2,
      //     CellCount: 6,
      //     PutRule: "top_left_v",
      //   },
      //   {
      //     BlockTypeId: "block6",
      //     BlockTypeName: "block6",
      //     LRow: 2,
      //     LColumn: 2,
      //     CellRow: 3,
      //     CellColumn: 2,
      //     CellCount: 6,
      //     PutRule: "top_right_v",
      //   },
      //   {
      //     BlockTypeId: "block7",
      //     BlockTypeName: "block7",
      //     LRow: 2,
      //     LColumn: 3,
      //     CellRow: 3,
      //     CellColumn: 2,
      //     CellCount: 6,
      //     PutRule: "bottom_left_v",
      //   },
      //   {
      //     BlockTypeId: "block8",
      //     BlockTypeName: "block8",
      //     LRow: 2,
      //     LColumn: 4,
      //     CellRow: 3,
      //     CellColumn: 2,
      //     CellCount: 6,
      //     PutRule: "bottom_right_v",
      //   },
      //   {
      //     BlockTypeId: "block1",
      //     BlockTypeName: "block1",
      //     LRow: 1,
      //     LColumn: 1,
      //     CellRow: 3,
      //     CellColumn: 2,
      //     CellCount: 6,
      //     PutRule: "top_left",
      //   },
      //   {
      //     BlockTypeId: "block2",
      //     BlockTypeName: "block2",
      //     LRow: 1,
      //     LColumn: 2,
      //     CellRow: 3,
      //     CellColumn: 2,
      //     CellCount: 6,
      //     PutRule: "top_right",
      //   },
      //   {
      //     BlockTypeId: "block3",
      //     BlockTypeName: "block3",
      //     LRow: 1,
      //     LColumn: 3,
      //     CellRow: 3,
      //     CellColumn: 2,
      //     CellCount: 6,
      //     PutRule: "bottom_left",
      //   },
      //   {
      //     BlockTypeId: "block4",
      //     BlockTypeName: "block4",
      //     LRow: 1,
      //     LColumn: 4,
      //     CellRow: 3,
      //     CellColumn: 2,
      //     CellCount: 6,
      //     PutRule: "bottom_right",
      //   },
      // ];
      // BlockDetails.sort((a, b) => {
      //   if (a.LRow !== b.LRow) {
      //     // 如果 LRow 不同，直接按照 LRow 排序
      //     return a.LRow - b.LRow;
      //   } else {
      //     // 如果 LRow 相同，则按照 LColumn 排序
      //     return a.LColumn - b.LColumn;
      //   }
      // });
      // console.log("如果 LRow 不同", BlockDetails);
    },
    // 通过计划找到当前块信息
    planSearchBlock(UniqueBlock) {
      let n = UniqueBlock.split("_")[1];
      let plan_search_block = this.kwInfo[0].BlockDetails.find((f) => f.n == n);
      //  console.log("UniqueBlock", n, plan_search_block);
      return plan_search_block;
    },
    // 下一步，完成，跳过参数
    getParams(type) {
      const [ProductLineCode, PointCode] = this.workBenchCode;
      let Detail = this.dealDetail().pop();
      let { BlockTypeId, UniqueBlock } = this.CurrentBlock();
      let { LRow, LColumn } = this.planSearchBlock(UniqueBlock);
      const {
        ProductOrder,
        ProductCode,
        SkuId,
        BarCodeNumber,
        PlanDate,
        PackSort,
        BoxCode,
        PointTaskBillId,
        TaskId,
        FlowNo,
        OrderLineNo,
        BatchNo,
      } = this.mergeMsg();
      console.log(
        "下一步，完成，跳过参数----->>>",
        this.CurrentBlock(),
        this.mergeMsg(),
        // this.dealDetail(),
        Detail,
        this.listItem
      );
      // let { ToCID } = Detail;
      // let ToLoc = this.kwInfo.find((f) => f.CIDCode == ToCID)?.LocationId;
      let res = {
        ...Detail,
        ProductLineCode,
        PlanDate,
        PackSort,
        // StationCode,
        PointCode,
        ProductOrder,
        ProductCode,
        BarCodeNumber,
        SkuId,
        BoxCode,
        TaskId,
        OrderLineNo,
        BatchNo,
        FlowNo,
        UserId: this.userName,
        PointTaskBillId,
        BlockTypeId,
        Row_Column: LRow + "-" + LColumn,
        // ToLoc,
      };
      if (type === "keyflagSkip") {
        let { ToCID } = Detail;
        let flatList = this.orderWarehouseList.flat(Infinity);
        let FNumList = flatList.filter((f) => !f.isCom && f.isWork);
        let ToLoc = this.kwInfo.find((f) => f.CIDCode == ToCID)?.LocationId;
        let Qty = 1;
        res = this.listItem.map((M, N) => {
          return {
            // FlowNo,
            // SkuId,
            // BarCodeNumber,
            // ProductCode,
            // ProductOrder,
            // ProductLineCode,
            // PointCode,
            ...res,
            FlowNo: FNumList[N]?.FlowNo,
            FromLoc: M.LocationId,
            FromCID: M.CIDCode,
            PlanDate: M.PlanDate,
            OrderLineNo: M.OrderLineNo,
            PointTaskBillId: M.PointTaskBillId,
            BatchNo: M.BatchNo,
            TaskId: M.TaskId,
            BoxCode: M.BoxCode,
            PackSort: M.PackSort,
            PlanDate: M.PlanDate,
            ToLoc,
            ToCID,
            Qty,
          };
        });
      }
      if (type === "many") {
        res = {
          ProductLineCode,
          PointCode,
          UserId: this.userName,
          OperationDetails: this.getDetailParmes().map((m) => ({
            ...m,
            BlockTypeId,
            Row_Column: LRow + "-" + LColumn,
          })),
        };
      }
      // return false;
      return res;
    },
    // 初始化
    init() {
      this.keyContinuousStatus = true;
      this.getQJ().then(() => {
        this.start();
      });
    },
    // 关键件扫描完成
    async keyflagComplete(data) {
      if (data.IsForceComplete == 1 && !this.forcedConfirmReason) {
        this.$message({
          type: "warning",
          message: "请填写强制确认原因",
        });
        return;
      }
      let iscross = this.btCompare();
      if (iscross) {
        this.$message({
          type: "warning",
          message: "投料点数量不足",
        });
        return;
      }
      const params = {
        data: {
          ...this.getParams(),
          PullNumber: this.scanCode,
          ...data,
          Reason: this.forcedConfirmReason,
        },
      };
      console.timeEnd();
      let [ERR, KRES] = await api.keyflagCompleteAPI(params);

      if (KRES.code === 0) {
        this.$message({
          type: "success",
          message: KRES.message,
        });
      }
      this.changeConfirm(KRES.changemessage, KRES);

      console.log("关键件扫描完成---->>>", params, KRES);

      this.keyVisible = false;
      if (KRES.iscomplete == 1) {
        let index = this.kwInfo.findIndex(
          (f) => f.CIDCode == params.data?.ToCID
        );
        this.open(index);
        this.COMPELETEBTN = false;
      }
      // if (KRES.ischangeblock != 1) {
      this.init();
      // }
    },
    // 关键件扫描完成修改
    async keyflagCompleteChange(data) {
      if (data.IsForceComplete == 1 && !this.forcedConfirmReason) {
        this.$message({
          type: "warning",
          message: "请填写强制确认原因",
        });
        return;
      }
      const { BarCodeNumber, BillId } = this.editorItem;
      const params = {
        data: {
          // BarCodeNumber,
          PullNumber: this.scanCode,
          BillId,
          UserId: this.userName,
          Reason: this.forcedConfirmReason,
          ...data,
        },
      };
      this.scanCode = "";
      let [ERR, KRES] = await api.keyflagCompleteChangeAPI(params);
      if (KRES.code === 0) {
        this.editorStatus = false;
        this.keyVisible = false;
        this.$message({
          type: "success",
          message: KRES.message,
        });
        this.init();
      }
      this.changeConfirm(KRES.changemessage, KRES);

      if (KRES.iscomplete == 1) {
        let index = this.kwInfo.findIndex(
          (f) => f.LocationId == params.data?.ToLoc
        );
        this.open(index);
      }
    },
    // 并列件不可跨层
    isCrossOver() {
      let res = false;
      let CidList = this.orderWarehouseList
        .flat(Infinity)
        .filter((f) => !f.isCom && f.isWork)
        .map((m) => m.CIDCode);
      const CidUnique = [...new Set(CidList)];
      if (CidUnique.length > 1) {
        res = true;
        this.$message.warning("并列件不可跨托盘提交");
      }
      // console.log(
      //   "并列件不可跨层",
      //   this.orderWarehouseList
      //     .flat(Infinity)
      //     .filter((f) => !f.isCom && f.isWork),
      //   unique
      // );
      return res;
    },
    // 并列件扫描完成
    async keyflagCompleteMore(data) {
      if (data.IsForceComplete == 1 && !this.forcedConfirmReason) {
        this.$message({
          type: "warning",
          message: "请填写强制确认原因",
        });
        return;
      }
      let iscross = this.btCompare();
      if (iscross) {
        this.$message({
          type: "warning",
          message: "投料点数量不足",
        });
        return;
      }
      // if (this.isCrossOver()) {
      //   return;
      // }
      let { CIDCode, TaskInfo } = this.listOutItem;
      let arr = [];
      if (TaskInfo?.length > 0) {
        let showList = TaskInfo.filter((f) => f.isShow);
        showList.forEach((item) => {
          if (item.Qty > 0) {
            let QtyList = Array(item.Qty).fill({ ...item, FromCID: CIDCode });
            arr.push(...QtyList);
          }
        });
      }
      // console.log("***************", arr);
      const params = {
        data: {
          ...this.getParams(),
          PullNumber: this.scanCode,
          ...data,
          BarCodeNumber: arr.map((m) => m.BarCodeNumber).join(","),
          FromCID: arr.map((m) => m.FromCID).join(","),
          PointTaskBillId: arr.map((m) => m.PointTaskBillId).join(","),
          TaskId: arr.map((m) => m.TaskId).join(","),
          OrderLineNo: arr.map((m) => m.OrderLineNo).join(","),
          BoxCode: arr
            .map((m) => {
              if (m.BoxCode) {
                return m.BoxCode;
              } else {
                return "NULL";
              }
            })
            .join(","),
          BatchNo: arr.map((m) => m.BatchNo).join(","),
        },
      };
      console.log(
        "关键件多个扫描完成--->>>",
        this.getParams(),
        data,
        this.scanCode
      );
      console.log("关键件多个扫描完成---->>>", params);

      let [ERR, KRES] = await api.keyflagCompleteAPI(params);
      // console.log("并列件扫描完成---->>>", params, KRES, ERR);
      if (KRES.code === 0) {
        this.$message({
          type: "success",
          message: KRES.message,
        });
      }
      this.init();
    },
    // 并列件扫描完成
    async BLJComplete(data) {
      if (data.IsForceComplete == 1 && !this.forcedConfirmReason) {
        this.$message({
          type: "warning",
          message: "请填写强制确认原因",
        });
        return;
      }
      let iscross = this.btCompare();
      if (iscross) {
        this.$message({
          type: "warning",
          message: "投料点数量不足",
        });
        return;
      }
      if (this.isCrossOver()) {
        return;
      }
      let { CIDCode, TaskInfo } = this.listOutItem;
      let arr = [];
      if (TaskInfo?.length > 0) {
        let showList = TaskInfo.filter((f) => f.isShow);
        showList.forEach((item) => {
          if (item.Qty > 0) {
            let QtyList = Array(item.Qty).fill({ ...item, FromCID: CIDCode });
            arr.push(...QtyList);
          }
        });
      }
      // console.log("***************", arr);
      const params = {
        data: {
          ...this.getParams(),
          PullNumber: this.scanCode,
          ...data,
          BarCodeNumber: arr.map((m) => m.BarCodeNumber).join(","),
          FromCID: arr.map((m) => m.FromCID).join(","),
          PointTaskBillId: arr.map((m) => m.PointTaskBillId).join(","),
          TaskId: arr.map((m) => m.TaskId).join(","),
          OrderLineNo: arr.map((m) => m.OrderLineNo).join(","),
          BoxCode: arr
            .map((m) => {
              if (m.BoxCode) {
                return m.BoxCode;
              } else {
                return "NULL";
              }
            })
            .join(","),
          BatchNo: arr.map((m) => m.BatchNo).join(","),
        },
      };
      console.log(
        "并列件扫描完成--->>>",
        this.getParams(),
        data,
        this.scanCode
      );
      console.log("并列件扫描完成11---->>>", params);

      let [ERR, KRES] = await api.keyflagCompleteAPI(params);
      // console.log("并列件扫描完成---->>>", params, KRES, ERR);
      if (KRES.code === 0) {
        this.$message({
          type: "success",
          message: KRES.message,
        });
      }
      this.init();
      this.isBLJ = false;
    },
    // 关键件扫描跳过
    async keyflagSkip() {
      let paramsList = this.getParams("keyflagSkip").map((m) => ({
        ...m,
        Reason: this.returnReason,
      }));
      if (paramsList.length > 0) {
        for (let i = 0; i < paramsList.length; i++) {
          try {
            const [ERR, KRES] = await api.keyflagSkiponeAPI({
              data: paramsList[i],
            });
            this.changeConfirm(KRES.changemessage, KRES);
            if (KRES.iscomplete == 1) {
              // let index = this.kwInfo.findIndex(
              //   (f) => f.LocationId == params.data?.ToLoc
              // );
              this.open(0);
            }
            console.log(`Data fetched:`, KRES);
          } catch (error) {
            console.error("Error fetching data:", error);
            break; // 如果发生错误，跳出循环
          }
        }
        // test.forEach(async(f) => {
        //   let [ERR, KRES] = await f;
        // })
        // Promise.all(test)
        //   .then((res) => {
        //     console.log("*******sbsbsbsbsbsbs******", res);
        //   })
        //   .catch((err) => {
        //     reject(err);
        //   });
      }
      // const params = {
      //   data: {
      //     ...this.getParams("keyflagSkip"),
      //     Reason: this.returnReason,
      //   },
      // };
      console.log("关键件扫描跳过", paramsList);
      // let [ERR, KRES] = await api.keyflagSkiponeAPI(params);
      // if (KRES.code === 0) {
      //   this.$message({
      //     type: "success",
      //     message: KRES.message,
      //   });
      // }

      this.init();
    },
    // 关键件扫描跳过修改
    async keyflagChangeSkip() {
      const { BillId } = this.editorItem;
      const params = {
        data: {
          BillId,
          UserId: this.userName,
          Reason: this.returnReason,
        },
      };
      let [ERR, KRES] = await api.keyflagSkiponeChangeAPI(params);
      if (KRES.code === 0) {
        this.editorStatus = false;
        this.keyVisible = false;
        this.$message({
          type: "success",
          message: KRES.message,
        });
        this.init();
      }
    },
    // 非关键件下一步
    async unkeyflagNextstep() {
      let iscross = this.btCompare();
      if (iscross) {
        this.$message({
          type: "warning",
          message: "投料点数量不足",
        });
        return;
      }
      const params = {
        data: {
          ...this.getParams("many"),
        },
      };
      let [ERR, KRES] = await api.unkeyflagNextstepAPI(params);
      console.log("非关键件下一步---->>>", params);

      if (KRES.code === 0) {
        this.$message({
          type: "success",
          message: KRES.message,
        });
      }
      this.changeConfirm(KRES.changemessage, KRES);
      if (KRES.iscomplete == 1) {
        let index = this.kwInfo.findIndex(
          (f) => f.CIDCode == params.data?.OperationDetails[0]?.ToCID
        );
        this.open(index);
        this.COMPELETEBTN = false;
      }
      this.init();
    },

    // 绑定弹窗确认
    async bindOk() {
      const { tp_num, kw_num } = this.form;
      const params = {
        data: {
          CIDCode: tp_num,
          LocationId: kw_num,
          UserId: this.userName,
        },
      };
      let [ERR, CRES] = await api.cidLocationBindAPI(params);
      if (CRES.code === 0) {
        this.getCidsInfo(this.workBenchCode);
        this.trayVisible = false;
      }
    },
    // 器具选择
    onChange(e) {
      this.QJ_Select = e;
    },

    Debounce_SkipLattic: _.debounce(function (data) {
      // 这里不能用箭头，不然获取不到 this 实例
      this.skipLattice(data);
    }, 500),

    // 跳过格口
    async skipLattice(num = 1) {
      const data = this.getParams();
      let skipnum = num;
      delete data.BoxCode;
      delete data.TaskId;
      delete data.OrderLineNo;
      delete data.BatchNo;
      delete data.FromCID;
      // delete data.PointTaskBillId;
      delete data.Qty;
      delete data.Reason;
      delete data.BlockTypeId;
      console.log("跳过格口", data);
      if (!this.started) {
        this.$message.warning("请先开始");
        return true;
      }
      const params = {
        data: {
          ...data,
          skipnum,
        },
      };
      console.log("跳过格口", params);
      let [, KRES] = await api.keyflagSkiponeGKAPI(params);
      if (KRES.code === 0) {
        this.$message({
          type: "success",
          message: KRES.message,
        });
      }
      this.init();
    },

    async skipLatticePlus(num = 1) {
      const data = this.getParams();
      //  const [ProductLineCode, PointCode] = this.workBenchCode;
      // const { CIDCode } = this.kwInfo[0];
      const { LRow, LColumn } = this.CurrentBlockLoc();
      let skipnum = num;
      delete data.BoxCode;
      delete data.TaskId;
      delete data.OrderLineNo;
      delete data.BatchNo;
      delete data.FromCID;
      // delete data.PointTaskBillId;
      delete data.Qty;
      delete data.Reason;
      console.log("跳过格口", data);
      if (!this.started) {
        this.$message.warning("请先开始");
        return true;
      }
      const params = {
        data: {
          ...data,
          skipnum,
          LRow,
          LColumn,
          PutRule: this.Put_Rule,
          isPresent: 0,
        },
      };
      console.log("跳过格口", params);
      let [, KRES] = await api.updatejdwBlockCidsAPI(params);
      if (KRES.code === 0) {
        this.$message({
          type: "success",
          message: KRES.message,
        });
      }
      this.init();
    },

    Debounce_KeyCancel: _.debounce(function () {
      this.keyCancel();
    }, 500),

    // 关键件扫描跳过
    keyCancel() {
      if (!this.returnReason) {
        this.$message({
          type: "warning",
          message: "跳过原因缺失",
        });
        return;
      } else {
        if (this.editorStatus) {
          this.keyflagChangeSkip();
        } else {
          this.keyflagSkip();
        }
      }
    },
    // 关键件弹窗
    showKeyModal(item) {
      this.orderWarehouseItem = item;
      let KeyFlag = item.KeyFlag;
      if (KeyFlag && this.rearEndkeyVisible) {
        this.keyVisible = true;
        this.scanCode = "";
        this.returnReason = "";
        this.forcedConfirmReason = "";
        // this.$nextTick(() => {
        //   this.$refs.inputValue.focus(); //聚焦
        // });
      }
      if (!this.rearEndkeyVisible) this.rearEndkeyVisible = true;
    },
    Debounce_KeyOk: _.debounce(function (data) {
      // 这里不能用箭头，不然获取不到 this 实例
      this.keyOk(data, "Debounce_KeyOk");
    }, 500),
    // 关键件和非关键件扫描弹窗确定
    keyOk(data, str = "") {
      console.time();
      console.log(
        "关键件和非关键件扫描弹窗确定 data, this.scanCode, str",
        data,
        this.scanCode,
        str
      );
      if (!this.scanCode) {
        this.$message({
          type: "warning",
          message: "扫描码缺失",
        });
        return;
      } else {
        if (this.editorStatus) {
          this.keyflagCompleteChange(data);
          // this.editorStatus = false;
        } else {
          if (this.isBLJ) {
            this.BLJComplete(data);
          } else {
            if (this.FkeyNum() > 1 && this.findSelf.KeyFlag) {
              this.keyflagCompleteMore(data);
            } else {
              this.keyflagComplete(data);
            }
          }
        }
      }
    },
    // 任务完成关闭弹窗
    hideModalClose() {
      let filterList = this.orderWarehouseList.filter((f) => f.length > 0);
      let res = filterList.flat(Infinity).every((e) => e.isCom);
      return res;
    },
    // 获取未完成项
    findFirstItem() {
      let findSelf = this.kwAccordCopyList.find(
        (f) => !f.isWork && !f.isCom && !f.BillId && !f.CID
      );
      this.findSelf = findSelf;
      return findSelf;
    },
    // 过滤出几项
    fliterFirstFlatItem() {
      let flatList = this.orderWarehouseList.flat(Infinity);
      let findItem = this.findFirstItem();
      let res = [];
      if (findItem) {
        res = flatList.filter(
          (f) =>
            f.ProductOrder === findItem.ProductOrder &&
            f.ProductCode === findItem.ProductCode &&
            f.SkuId === findItem.SkuId
        );
      }
      return res;
    },
    // 过滤出几项
    fliterFirstItem() {
      // let flatList = this.orderWarehouseList.flat(Infinity);
      let flatList = this.kwAccordList;
      let findItem = this.findFirstItem();
      let res = [];
      if (findItem) {
        res = flatList.filter(
          (f) =>
            f.ProductOrder === findItem.ProductOrder &&
            f.ProductCode === findItem.ProductCode &&
            f.SkuId === findItem.SkuId
        );
      }
      return res;
    },
    // 处理块数据方向
    BlockDirection(BlockSliceList, BlockItem) {
      // console.log("处理块数据方向", BlockSliceList, BlockItem);
      let list = BlockSliceList;
      if (BlockItem.PutRule == "bottom_left") {
        BlockSliceList = BlockSliceList.reverse();
        let res = [];
        for (let i = 0; i < BlockItem.CellRow; i++) {
          let slice = BlockSliceList.slice(
            i * BlockItem.CellColumn,
            (i + 1) * BlockItem.CellColumn
          ).reverse();
          res.push(...slice);
        }
        list = res;
      }
      if (BlockItem.PutRule == "top_right") {
        let res = [];
        for (let i = 0; i < BlockItem.CellRow; i++) {
          let slice = BlockSliceList.slice(
            i * BlockItem.CellColumn,
            (i + 1) * BlockItem.CellColumn
          ).reverse();
          res.push(...slice);
        }
        list = res;
      }
      if (BlockItem.PutRule == "bottom_right") {
        list = BlockSliceList.reverse();
      }
      if (BlockItem.PutRule == "top_left_v") {
        let res = [];
        for (let i = 0; i < BlockItem.CellColumn; i++) {
          let slice = BlockSliceList.slice(
            i * BlockItem.CellRow,
            (i + 1) * BlockItem.CellRow
          );
          res.push(slice);
        }
        // 假设所有子数组的长度都相同
        const length = res[0].length;
        // 使用map来遍历列，并收集每列的元素
        res = Array.from({ length }, (_, colIndex) =>
          res.map((row) => row[colIndex])
        );
        list = [].concat(...res);
      }
      if (BlockItem.PutRule == "top_right_v") {
        let res = [];
        for (let i = 0; i < BlockItem.CellColumn; i++) {
          let slice = BlockSliceList.slice(
            i * BlockItem.CellRow,
            (i + 1) * BlockItem.CellRow
          );
          res.push(slice);
        }
        res = res.reverse();
        // 假设所有子数组的长度都相同
        const length = res[0].length;
        // 使用map来遍历列，并收集每列的元素
        res = Array.from({ length }, (_, colIndex) =>
          res.map((row) => row[colIndex])
        );
        list = [].concat(...res);
      }
      if (BlockItem.PutRule == "bottom_left_v") {
        let res = [];
        BlockSliceList = BlockSliceList.reverse();
        for (let i = 0; i < BlockItem.CellColumn; i++) {
          let slice = BlockSliceList.slice(
            i * BlockItem.CellRow,
            (i + 1) * BlockItem.CellRow
          );
          // console.log('BlockDirection', slice);
          res.push(slice);
        }
        // console.log('BlockDirection_res', res);
        res = res.reverse();
        // 假设所有子数组的长度都相同
        const length = res[0].length;
        // 使用map来遍历列，并收集每列的元素
        res = Array.from({ length }, (_, colIndex) =>
          res.map((row) => row[colIndex])
        );
        list = [].concat(...res);
        // console.log(
        //   "BlockDirection, bottom_left_v",
        //   list,
        //   BlockItem,
        //   BlockItem.CellRow,
        //   res
        // );
      }
      if (BlockItem.PutRule == "bottom_right_v") {
        let res = [];
        BlockSliceList = BlockSliceList.reverse();
        for (let i = 0; i < BlockItem.CellColumn; i++) {
          let slice = BlockSliceList.slice(
            i * BlockItem.CellRow,
            (i + 1) * BlockItem.CellRow
          );
          res.push(slice);
        }
        // 假设所有子数组的长度都相同
        const length = res[0].length;
        // 使用map来遍历列，并收集每列的元素
        res = Array.from({ length }, (_, colIndex) =>
          res.map((row) => row[colIndex])
        );

        list = [].concat(...res);
      }
      return list;
    },
    // 计划匹配
    matchMapList(list, CIDCode, BlockItem, BlockIndex) {
      let findSelf = this.findFirstItem();
      let longList = list.map((m, m_index) => {
        let commonData = {
          ...m,
          CIDCode,
          BlockTypeId: BlockItem.BlockTypeId,
          // 确实块得唯一性
          UniqueBlock: BlockItem.BlockTypeId + "_" + BlockIndex,
          isSelect: false,
        };
        if (findSelf && m) {
          if (findSelf.KeyFlag) {
            if (m.ScanQty == 1) {
              if (
                m.ProductOrder === findSelf.ProductOrder &&
                m.ProductCode === findSelf.ProductCode &&
                m.SkuId === findSelf.SkuId
              ) {
                if (this.isSkuIdMatching("aaaa").tag) {
                  this.isContinue = true;
                  return {
                    ...m,
                    CIDCode,
                    BlockTypeId: BlockItem.BlockTypeId,
                    UniqueBlock: BlockItem.BlockTypeId + "_" + BlockIndex,
                    isWork: true,
                    isSelect: false,
                  };
                } else {
                  return commonData;
                }
              } else {
                return commonData;
              }
            } else if (m.ScanQty == 0) {
              if (
                m.ProductCode === findSelf.ProductCode &&
                m.SkuId === findSelf.SkuId &&
                m.FlowNo === findSelf.FlowNo
                // && this.keyContinuousStatus
              ) {
                // console.log(
                //   "m.ScanQty",
                //   !m.isCom,
                //   m_index < this.kwAccordList.length - 1
                // );
                // if (
                //         !m.isCom &&
                //         m_index < this.kwAccordList.length - 1 &&
                //         (m.ProductCode !==
                //           this.kwAccordList[m_index + 1].ProductCode ||
                //           m.SkuId !== this.kwAccordList[m_index + 1].SkuId)
                //       ) {
                //         console.log(
                //           "m.ScanQty == 0",
                //           "mmmm",
                //           m_index,
                //           m.ProductCode,
                //           this.keyContinuousStatus
                //         );
                //         this.keyContinuousStatus = false;
                //       }
                if (this.isSkuIdMatching("bbbbb").tag) {
                  this.isContinue = true;
                  // iii += 1;
                  return {
                    ...m,
                    CIDCode,
                    BlockTypeId: BlockItem.BlockTypeId,
                    UniqueBlock: BlockItem.BlockTypeId + "_" + BlockIndex,
                    isWork: true,
                    isSelect: false,
                  };
                } else {
                  return commonData;
                }
              } else {
                return commonData;
              }
            } else {
              return commonData; //自己填充进来的数据可能会没有ScanQty字段
            }
          } else {
            if (
              !m.isCom &&
              m.BarCodeNumber === findSelf.BarCodeNumber &&
              m.FlowNo === findSelf.FlowNo
            ) {
              if (m.KeyFlag) {
                this.isContinue = false;
              }
              if (this.isSkuIdMatching("ccccc").tag && this.isContinue) {
                return {
                  ...m,
                  CIDCode,
                  BlockTypeId: BlockItem.BlockTypeId,
                  UniqueBlock: BlockItem.BlockTypeId + "_" + BlockIndex,
                  isWork: true,
                  isSelect: true,
                };
              } else {
                return commonData;
              }
            } else {
              return commonData;
            }
          }
        } else {
          return commonData;
        }
      });
      return longList;
    },
    // 块内相同ScanQty=0做标记，以至于同步亮
    BlcokScanQty(BlockSliceList) {
      let skus = BlockSliceList.filter((m) => m.ScanQty == 0).map(
        (m) => m.SkuId
      );
      console.log("BlockSliceList", BlockSliceList, skus);
    },
    CurrentBlockLoc() {
      return this.kwInfo[0].BlockDetails.find(
        (f) => f.n == this.BlockHighlight()
      );
    },
    beforeBlockComplete(n) {
      let status = false;
      if (n > 0) {
        let Previous_n = n - 1;
        let Previous_list = this.orderWarehouseList[Previous_n];
        status = Previous_list.every((e) => e.isWork && e.isCom && !e.complete);
      }
      if (n == 0) {
        status = true;
      }
      // console.log("beforeBlockComplete", n, status);
      return status;
    },
    // 换块预警
    ChangeBlockTip() {
      // 当前第几个块高亮
      let n = this.BlockHighlight();
      let findSelf = this.findFirstItem();
      console.log("换块预警2", n, this.rearEnd);
      // this.beforeBlockComplete(n);
      if (
        this.beforeBlockComplete(n) &&
        n > -1 &&
        this.rearEnd &&
        findSelf.BlockTypeId
      ) {
        let str = `请在指定位置放置${findSelf.BlockTypeId}类型的块 , 是否继续?`;
        this.$confirm(str, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            // 前端提示的换块默认给1
            this.updatejdwBlockCids(1, {}, "client");
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
      this.rearEnd = true;
    },
    // 数据重绘
    redrawGrid() {
      const sortWhichList = this.capLocationStart(); //[0,1]
      let BlockData = [];
      sortWhichList.forEach((ITEM) => {
        let { BlockDetails, CIDCode } = this.kwInfo[ITEM];
        let factIndex = 0;
        BlockDetails.forEach((BlockItem, BlockIndex) => {
          const { CellCount } = BlockItem;
          if (CellCount) {
            let BlockSliceList = this.kwAccordList.slice(
              factIndex * CellCount,
              (factIndex + 1) * CellCount
            );
            factIndex = factIndex + 1;
            // 当计划小于块的格子数量时自动补齐数据
            if (BlockItem.CellCount > BlockSliceList.length) {
              let concatArr = Array(
                BlockItem.CellCount * 1 - BlockSliceList.length
              ).fill({
                isWork: false,
                ProductOrder: "",
                isCom: false,
              });
              BlockSliceList = BlockSliceList.concat(...concatArr);
            }
            console.log(
              "redrawGrid_BlockItem_111",
              BlockIndex,
              BlockItem,
              BlockSliceList
              // this.BlockDirection(BlockSliceList, BlockItem)
            );
            // this.BlcokScanQty(BlockSliceList);
            BlockData[BlockIndex] = this.matchMapList(
              this.BlockDirection(BlockSliceList, BlockItem),
              CIDCode,
              BlockItem,
              BlockIndex
            );
            console.log(
              "redrawGrid_BlockItem",
              BlockIndex,
              // BlockItem,
              BlockSliceList
              // this.BlockDirection(BlockSliceList, BlockItem),
              // this.matchMapList(
              //   this.BlockDirection(BlockSliceList, BlockItem),
              //   CIDCode,
              //   BlockItem,
              //   BlockIndex
              // )
            );
          } else {
            BlockData[BlockIndex] = [];
          }
        });

        this.orderWarehouseList = BlockData;
        // 换块预警提示
        this.ChangeBlockTip();
        console.log(
          "redrawGrid",
          ITEM,
          this.kwInfo[ITEM],
          this.kwAccordList,
          BlockData
        );
      });
    },
    // 增强版下一步
    lunPlus() {
      this.redrawGrid();
      if (this.anOperableTray()) {
        // this.$message({
        //   type: "warning",
        //   message: "当前无可用托盘",
        // });
        return;
      }
      if (this.findSelf && this.codeTypeMAS()) {
        const { CTypeCode } = this.kwInfo[0];
        this.msgCardShow = false;
        this.$message({
          type: "warning",
          duration: 10000,
          showClose: true,
          message: `当前精定位托盘器具类型(${CTypeCode})与当前计划件号(${this.findSelf?.SkuId})对应器具类型(${this.findSelf?.CTypeCode})不符`,
        });
        return;
      }
      if (this.promptComplete().isPromptComplete && this.COMPELETEBTN) {
        this.open(this.promptComplete().completeIndex);
        this.COMPELETEBTN = true;
        return;
      }
      if (this.isSkuIdMatching("ddddd")?.tag) {
        if (this.hideModalClose()) {
          this.$message({
            type: "warning",
            message: "当前无任务",
          });
          this.msgCardShow = false;
          return;
        }

        if (this.findSelf) this.showKeyModal(this.findSelf);
      }
    },
    // 清空器具状态
    clearRandomListStatus() {
      this.listData = this.listData.map((m) => {
        return {
          ...m,
          qj_active: false,
          TaskInfo: m.TaskInfo?.map((n) => ({ ...n, isShow: false })),
        };
      });
    },
    // 通过的数组
    passesArray(arr, needNum) {
      let showList = [];
      let sum = 0;
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].Qty > 0) {
          sum = sum + arr[i].Qty;
          if (sum <= needNum) {
            // console.log("通过的数组**********", arr, sum);
            showList.push(arr[i]);
          }
          // break;
        }
      }
      return showList;
    },
    getMaterialInventory() {
      let matchList = this.listItem[0]?.TaskInfo?.filter(
        (f) => f.SkuId == this.findSelf?.SkuId
      );
      const Qty = matchList.reduce((pre, cur) => {
        return pre + cur.Qty;
      }, 0);
      this.MaterialInventory = {
        SkuName: matchList[0]?.SkuName,
        SkuId: matchList[0]?.SkuId,
        Qty,
      };
    },
    FkeyNum() {
      let n = 1;
      let flatList = this.orderWarehouseList.flat(Infinity);
      let FNum = flatList.filter((f) => !f?.isCom && f?.isWork);
      n = FNum?.length > 0 ? FNum?.length : n;
      // console.log("FkeyNum", flatList, FNum);
      return n;
    },
    // 是否能匹配到物料
    SkuIdMatchingNumber() {
      let arr = [];
      if (this.findFirstItem()) {
        let { PackSort, PlanDate, BarCodeNumber, SkuId } = this.findFirstItem();
        this.listData.forEach((fItem, fIndex) => {
          fItem.TaskInfo?.forEach((item, index) => {
            if (
              item.PackSort == PackSort &&
              item.PlanDate == PlanDate &&
              item.BarCodeNumber == BarCodeNumber &&
              item.SkuId == SkuId
            ) {
              arr.push({ ...item, coordinates: [fIndex, index] });
            }
          });
        });
      }
      // console.log('m.ScanQty == 0 2 3', arr);
      return arr.length;
    },
    // 是否能匹配到物料
    isSkuIdMatching(a) {
      // console.log('lunPlus====是否能匹配到物料',a, this.findFirstItem());
      if (!this.findFirstItem()) {
        // this.$message.warning("未匹配到物料");
        return;
      }
      let pp = 100;
      let cc = 100;
      let tag = false;
      let arr = [];
      let {
        PackSort,
        PlanDate,
        BarCodeNumber,
        SkuId,
        Qty,
        KeyFlag,
        SupplierCode,
      } = this.findFirstItem();
      // let filterList = this.fliterFirstItem();
      // let needNum = filterList.length;
      let needNum = this.FkeyNum(); //4/26关闭
      // let needNum = 1
      if (KeyFlag) {
        if (/^&+/.test(this.scanCode)) {
          needNum = this.scanCode.split("&").pop() * 1; //大于0
        } else {
          if (needNum < 2) {
            needNum = Qty * 1;
          }
        }
      }
      let Conditions = () => true;
      if (SupplierCode) {
        Conditions = (item) => {
          return item.SupplierCode === SupplierCode;
        };
      }
      this.listData.forEach((fItem, fIndex) => {
        fItem.TaskInfo?.forEach((item, index) => {
          // console.log("pppppppppppppppppppppppppp", a);
          if (
            item.PackSort == PackSort &&
            item.PlanDate == PlanDate &&
            item.BarCodeNumber == BarCodeNumber &&
            item.SkuId == SkuId &&
            Conditions(item)
          ) {
            arr.push({ ...item, coordinates: [fIndex, index] });
          }
        });
      });

      let res = this.passesArray(arr, needNum);
      // console.log(
      //   "通过的数量----->>>",
      //   this.findFirstItem(),
      //   filterList,
      //   needNum,
      //   res
      // );
      let passesList = [];
      if (res.length > 0) {
        tag = true;
        this.MatchingTag = true;
        passesList = res.map((m) => ({ coordinates: m.coordinates }));
        pp = passesList[0];
        cc = passesList[1];
      }
      console.log("是否能匹配到物料", a, tag, arr, res, needNum, passesList);
      return { tag, pp, cc, passesList };
    },
    // 退空的器具删缓存
    resetSelectLocationIdList(LocationId) {
      if (sessionStorage.getItem("selectLocationIdList")) {
        let sessionList = JSON.parse(
          sessionStorage.getItem("selectLocationIdList")
        );
        let newSessionList = removeListItem(sessionList, LocationId);
        this.selectLocation = newSessionList;
        // console.log("退空的器具删缓存", newSessionList);
        sessionStorage.setItem(
          "selectLocationIdList",
          JSON.stringify(newSessionList)
        );
      }
    },
    // 需要请退空的器具
    saveSelectLocationIdList(locationId) {
      if (sessionStorage.getItem("selectLocationIdList")) {
        let sessionList = JSON.parse(
          sessionStorage.getItem("selectLocationIdList")
        );
        sessionList.push(locationId);
        sessionList = [...new Set(sessionList)];
        this.selectLocation = sessionList;
        sessionStorage.setItem(
          "selectLocationIdList",
          JSON.stringify(sessionList)
        );
      } else {
        sessionStorage.setItem("selectLocationIdList", JSON.stringify([]));
      }
    },
    // 器具信息匹配
    randomLun() {
      if (this.MatchingTag) {
        let QJListData = [];
        let passesList = this.isSkuIdMatching("eeeeee").passesList;
        if (passesList.length > 0) {
          this.clearRandomListStatus();
          passesList.forEach((p) => {
            let pp = p.coordinates[0];
            let cc = p.coordinates[1];
            // console.log(
            //   "器具信息匹配",
            //   passesList,
            //   pp,
            //   cc,
            //   this.listData[pp].TaskInfo[cc]
            // );
            this.listData[pp].TaskInfo[cc]["isShow"] = true;
            this.listData[pp]["qj_active"] = true;
            this.saveSelectLocationIdList(this.listData[pp]?.LocationId);
            this.rolling(pp, cc);
            this.listOutItem = this.listData[pp];
            QJListData.push({
              ...this.listData[pp].TaskInfo[cc],
              ...this.listData[pp],
            });
          });
          this.listItem = QJListData;
          // console.log("器具信息匹配---->>>", QJListData);
        }
      }
    },

    // 提示是否有已经完成的托盘
    promptComplete() {
      let completeIndex = 0;
      let isFullCom = false;
      if (
        this.orderWarehouseList.flat(2).length == this.getCount() &&
        this.orderWarehouseList.flat(2).every((e) => e.isCom && !e.complete)
      ) {
        // 暂且关闭 4/25
        // isFullCom = false;
        isFullCom = true;
      }
      if (isFullCom) {
        return {
          isPromptComplete: true,
          completeIndex,
        };
      } else {
        return {
          isPromptComplete: false,
          completeIndex,
        };
      }
    },
    // 全局第几项下标
    getNextstepIndex() {
      let stepIndex = 0;
      this.orderWarehouseList.forEach((item, index) => {
        let res = item.flat(2);
        if (res.every((e) => e.isCom)) {
          stepIndex = index === 0 ? 1 : 0;
        }
        this.stepIndex = stepIndex;
      });
    },
    // 合并投料信息
    mergeMsg() {
      return {
        ...this.orderWarehouseItem,
        ...this.listItem[0],
        ...this.listOutItem,
      };
    },
    // 保证投料点数量大于等于库位
    btCompare() {
      let res = false;
      let tList = this.kwAccordList.filter(
        (kw) =>
          kw.PackSort === this.findSelf.PackSort &&
          kw.PlanDate === this.findSelf.PlanDate &&
          kw.BarCodeNumber === this.findSelf.BarCodeNumber &&
          kw.SkuId === this.findSelf.SkuId
      );
      let tQty = this.findSelf.Qty * 1;
      // tList.length;
      let bQty = this.listItem[0]?.Qty * 1;
      console.log("保证投料点数量大于等于库位", tList, tQty, bQty);

      if (tQty > bQty) {
        res = true;
      }
      return res;
    },
    // 物料投送详情信息
    messageSend() {
      if (this.orderWarehouseItem) {
        let fliterFirst = this.fliterFirstFlatItem();
        const BarCodeNumber = this.listItem[0].BarCodeNumber;
        const { SkuName, Qty, ProductCode, OrderNumber, SkuId } =
          this.orderWarehouseItem;
        const originCIDNameList = this.listItem.map((m) => m.CIDCode);
        const originCIDName = [...new Set(originCIDNameList)].join(",");
        const CIDCodeList = fliterFirst.map((m) => m.CIDCode);
        const CIDName = [...new Set(CIDCodeList)].join(",");
        this.msgCardInfo = {
          originCIDName,
          BarCodeNumber,
          SkuName,
          Qty,
          CIDName,
          ProductCode,
          OrderNumber,
          SkuId,
        };
      }
    },
    // msg通知交互
    setMsgCard() {
      if (this.MatchingTag) {
        this.msgCardShow = true;
        this.$refs.msgRef.$el.className = "box animated bounceInLeft";
        this.messageSend();
        this.getMaterialInventory();
        setTimeout(() => {
          this.$refs.msgRef.$el.className = "";
        }, 1000);
      }
    },
    Debounce_NextStepJK: _.debounce(function () {
      // 这里不能用箭头，不然获取不到 this 实例
      this.nextStepJK();
    }, 500),
    // 下一步接口
    nextStepJK() {
      if (this.findSelf && this.codeTypeMAS()) {
        const { CTypeCode } = this.kwInfo[0];
        this.msgCardShow = false;
        this.$message({
          type: "warning",
          duration: 15000,
          showClose: true,
          message: `当前精定位托盘器具类型(${CTypeCode})与当前计划件号(${this.findSelf?.SkuId})对应器具类型(${this.findSelf?.CTypeCode})不符`,
        });
        return;
      }
      const stepIndex = this.stepIndex;
      const c = this.kwInfo[stepIndex]?.c;
      const p = this.kwInfo[stepIndex]?.p;
      if (this.started) {
        // console.log("下一步接口");
        if (this.promptComplete().isPromptComplete) {
          this.open(this.promptComplete().completeIndex);
          return;
        }
        if (this.hideModalClose()) {
          this.$message({
            type: "warning",
            message: "当前无任务",
          });
          this.msgCardShow = false;
          return;
        }
        if (!this.MatchingTag) {
          this.$message({
            type: "warning",
            message: "未匹配到物料",
          });
          this.msgCardShow = false;
          return;
        }
        if (this.promptComplete().isPromptComplete) {
          this.open(this.promptComplete().completeIndex);
          return;
        }
        if (this.MatchingTag) {
          this.unkeyflagNextstep(stepIndex, p, c);
        }
      } else {
        this.$message({
          type: "warning",
          message: "请先点击开始",
        });
        return;
      }
    },
    open(completeIndex) {
      let { CIDName } = this.kwInfo[completeIndex];
      this.$confirm(`请先完成${CIDName}, 是否继续?`, `提示`, {
        showClose: false,
        showCancelButton: false,
        confirmButtonText: "确定",
        // cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.kwComplete(completeIndex);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 判断计划器具类型和托盘类型相同否
    codeTypeMAS() {
      const { CTypeCode } = this.kwInfo[0];
      let mas = false;
      if (CTypeCode != this.findSelf?.CTypeCode) mas = true;
      return mas;
    },
    // 下一步
    nextStep() {
      this.getNextstepIndex();
      this.keyVisible = false;
      if (this.started) {
        this.lunPlus();
        if (!this.MatchingTag) {
          this.$message({
            type: "warning",
            message: "未匹配到物料",
          });
          this.msgCardShow = false;
          return;
        }

        if (this.anOperableTray()) {
          this.$message({
            type: "warning",
            message: "当前无可用托盘",
          });
          this.msgCardShow = false;
          return;
        }
        if (this.hideModalClose()) {
          this.$message({
            type: "warning",
            message: "当前无任务",
          });
          this.msgCardShow = false;
          return;
        }
        if (this.codeTypeMAS()) {
          return;
        }
        this.randomLun();
        if (!this.promptComplete().isPromptComplete) {
          this.setMsgCard();
        }
      } else {
        this.$message({
          type: "warning",
          message: "请先点击开始",
        });
        return;
      }
    },
  },
};
</script>

<style scoped lang="scss">
// table tr { float:left;transform:rotate(90deg);}
// table td { transform: rotate(-90deg); }
.vCenter {
  // position: absolute;
  // top: 0;
  // bottom: 0;
  // left: 0;
  // right: 0;
  // margin: auto;
}
.material-inventory {
  display: flex;
  padding: 5px 10px;
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
  font-weight: bold;
}

.top_left_v {
  transform: rotate(90deg) rotateX(180deg); //左上v
}
.bottom_left_v {
  transform: rotate(-90deg); //左下v
}
.bottom_right_v {
  transform: rotate(-90deg) rotateX(180deg); //右下v
}
.top_right_v {
  transform: rotate(90deg); //右上v
}

.B_top_left_block_top_left_v {
  transform: rotateY(0deg); //右上v（文字）
}
.top_left_block_v {
  transform: rotateX(180deg); //右上v（文字）
}
.bottom_right_block {
  transform: rotateX(180deg) rotateY(180deg); //右上v（文字）
}
.b_top_right {
  transform: rotateY(180deg); //右上v（文字）
}
.b_top_right_txt {
  transform: rotateY(0deg); //右上v（文字）
}
.top_left_txt_v {
  transform: rotateX(180deg); //右上v（文字）
}
.bottom_left_txt_v {
  transform: rotate(90deg); //左下v（文字）
}
// .bottom_left_txt {
//   transform: rotateX(180deg); //左下v（文字）
// }
.top_right_txt_v {
  transform: rotate(270deg); //右上v（文字）
}
.bottom_right_txt_v {
  transform: rotate(-90deg) rotateX(180deg); //右下v（文字）
}

.top_left {
  transform: rotate(0deg); //左上
}
.bottom_left {
  transform: rotateX(180deg); //左下
}
.top_right {
  transform: rotateY(180deg); //右上
}
.bottom_right {
  transform: rotate(180deg); //右下
}
.qj_active {
  // color: #40a9ff;
  color: #fff;
  /deep/ .ant-card-head {
    color: unset;
    background: #40a9ff;
  }
}
/deep/ .ant-card-head-title {
  font-weight: bold;
}
/deep/ .ant-card .ant-card-body {
  height: 20vh;
  overflow: auto;
  padding: 0 !important;
  // background: #13c2c2;
}
/deep/ .ant-modal {
  // top: 700px !important;
}
.msg_card {
  position: fixed;
  top: 8px;
  left: 10px;
  z-index: 1001;
}
.legend_card {
  position: fixed;
  top: 10vh;
  right: 20px;
  z-index: 9;
}
.work-space {
  text-align: center;
}
.init_area {
  background: #f5f5f5;
  width: 40vw;
  height: 40vh;
}
.block-boundary {
  display: flex;
  gap: 5px; /* 上下左右间距 */
  margin-top: 10px;
}
.block-boundary-cell {
  border: 1px solid #000;
  position: relative;
}
.block-boundary-cell-hight {
  border: 3px solid #ff4d4f;
  position: relative;
}
.avatar {
  display: flex;
  align-items: center;
  margin-left: 25px;
  cursor: pointer;
  .icon {
    width: 30px;
    height: 30px;
  }
}
.title {
  padding: 10px 0;
  font-weight: 600;
  text-align: center;
  box-sizing: border-box;
  margin-bottom: 25px;
}
.login-name {
  color: #000;
  padding: 0 5px;
  font-weight: bold;
}
.ku_wei {
  margin: auto;
  width: 100%;
  display: flex;
  min-height: 40vh;
  justify-content: space-around;
  // border: 1px solid #000;
}
.cap {
  color: #000;
  font-size: 20px;
  padding: 0;
  text-align: center;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  cursor: pointer;
}
.vCap {
  position: relative;
  top: -30px;
  padding: 0;
}
.cap-td {
  width: 120px;
  height: 120px;
}
.ku_fixed {
  position: relative;
  // border: 2px solid #5d0dc7;
  //min-width: 40vw;
  //   border: 1px solid red;
  display: flex;
  flex-flow: column;
  justify-content: space-between;
}

.btn-group {
  width: 74vw;
  margin: auto;
  display: flex;
  justify-content: space-between;
  .sizeF {
    display: flex;
    width: 8vw;
    align-items: center;
    justify-content: center;
  }
  .size3 {
    display: flex;
    width: 8vw;
    align-items: center;
    justify-content: center;
  }
  .sizeT {
    display: flex;
    width: 6vw;
    align-items: center;
    justify-content: center;
  }
}
.kw-title {
  position: absolute;
  width: 35px;
  left: -35px;
  height: 40vh;
  font-size: 20px;
  bottom: 0;
  writing-mode: vertical-lr;
  text-align: center;
  font-weight: bold;
  color: rgba(0, 0, 0, 0.85);
  .kw-code {
    color: rgba(0, 0, 0, 0.65);
    font-weight: normal;
    font-size: 16px;
  }
}
.btn-group-fix {
  position: absolute;
  //   right: -90px;
  bottom: 0px;
  .item-btn {
    width: 5vw;
    font-size: 14px;
    text-align: center;
  }
}
.qi_ju {
  margin-top: 40px;
  .qi_ju_area {
    display: flex;
    justify-content: space-around;
    padding: 0 20px;
  }
  .qj-list-item {
    .name {
      color: #000;
      font-size: 14px;
      font-weight: bold;
      letter-spacing: 2px;
    }
  }
}
table {
  border-collapse: collapse;
  margin: auto;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}
table,
td,
th {
  /* border: 1px solid #f0f0f0; */
  border: 1px solid #d9d9d9;
}
.info {
  background: #f5f5f5;
  border: 2px solid #fff;
  box-sizing: border-box;
}
.bg_blue {
  background: #40a9ff;
  // background: #afdaf0;
}
.bg_cyan {
  background: #13c2c2;
}
.bg_red {
  background: #ff4d4f;
}
.bg_yellow {
  background: #ffe58f;
}
.bg_green {
  background: #b7eb8f;
}
.bg_pink {
  background: #f5f5f5 !important;
  // background: #fff !important;
}
.bg_complete {
  // background: #40a9ff;
  background: #722ed1;
}
.ku_wei /deep/ .ant-btn-group > .ant-btn:first-child:not(:last-child) {
  display: none !important;
}
/deep/ .ant-card {
  width: 100%;
}
/deep/ .ant-checkbox-wrapper {
  position: relative;
  display: block;
  margin: 0 10px;
}
/deep/ .ant-checkbox {
  position: absolute;
  left: -30px;
  top: 40px;
  display: none;
}
.ant-card /deep/ .ant-card-head-title {
  padding: 10px 0;
}
.ant-card /deep/ .ant-list-item {
  // padding: 6px 0;
}
.ant-card /deep/ .ant-card-body {
  padding: 0 24px;
}
.ant-card /deep/ .ant-card-head {
  min-height: 40px;
}
.btn-group {
  padding: 15px 0 30px 0;
}
.menu {
  position: fixed;
  top: 20px;
  right: 50px;
  .work-bench {
    display: flex;
    align-items: center;
    .mask {
      position: absolute;
      left: 0;
      z-index: 9;
      width: 65%;
      height: 100%;
    }
  }
}
/deep/ .ant-notification {
  height: 200px;
  //border: 1px solid red;
}
// .pull_txt {
//   max-width: 100px;
//   overflow: hidden;
//   white-space: nowrap;
//   text-overflow: ellipsis;
// }
</style>
